I'm learning unit testing. So far I was able to run simple tests like "Add two numbers and test if they are above 0", but I want to build a REST API using TDD. So far I have this:
My routes/index.js
file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res, next) {
res.send({val: true});
});
module.exports = router;
My index.test.js
file:
var mocha = require('mocha');
var assert = require('chai').assert;
var index = require('../routes/index');
describe('Index methods', () => {
it('Returns true', done => {
index
.get('http://localhost:3000')
.end(function (res) {
expect(res.status).to.equal(200);
done();
})
})
});
I user a tutorial to do this, but when I try to run this I get:
TypeError: index.get(...).end is not a function
So I'm guessing there is something wrong, but have no idea what. That's my first day learning TDD so if you see anything stupid please let me know.
Doing this:
it('Returns true', done => {
var resp = index.get('http://localhost:3000/');
assert.equal(resp.val === true);
done();
})
Also results in an error:
AssertionError: expected false to equal undefined
'use strict';
/*eslint no-console: ["error", { allow: ["warn", "error", "log"] }] */
const express = require('express');
const app = express();
//...
const config = require('config');
const port = process.env.PORT || config.PORT || 3000;
//....
app.listen(port);
console.log('Listening on port ' + port);
module.exports = app;
If your test script is users.spec.js,it should start by:
// During the rest the en variable is set to test
/* global describe it beforeEach */
process.env.NODE_ENV = 'test';
const User = require('../app/models/user');
// Require the dev-dependencies
const chai = require('chai');
const chaiHttp = require('chai-http');
// You need to import your server
const server = require('../server');
const should = chai.should();
// Set up the chai Http assertion library
chai.use(chaiHttp);
// Your tests
describe('Users', () => {
beforeEach((done) => {
User.remove({}, (err) => {
done();
});
});
/**
* Test the GET /api/users
*/
describe('GET /api/users', () => {
it('it should GET all the users', (done) => {
chai.request(server)
.get('/api/users')
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('array');
res.body.length.should.be.eql(0);
done();
});
});
});
// More test...
});
You can take a look at my repository, Github - Book Store REST API