简体   繁体   中英

Unit testing using Mocha with Express Rest API

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
const chai = require('chai');
const expect = require('chai').expect;
const chaiHttp = require('chai-http');
chai.use(chaiHttp);    

first install chai

it('Returns true', done => {
            return chai.request(index)
                .get('/')
                .then(function (res) {
                    expect(res.status).to.equal(200);
                    done();
                })
        })
var mocha = require('mocha');
var assert = require('chai').assert;
var index = require('./index');
var req = require('supertest');

describe('Index methods', () => {
    it('Returns true', done => {
        req(index)
            .get('/')
            .end(function (res) {
                expect(res.status).to.equal(200);
                done();
            })
    })
});

also in your terminal type npm i supertest --save-dev

1. Install the dev dependencies for mocha

  • chai : assertion library for node and browser,
  • chai-http : HTTP Response assertions for the Chai Assertion Library.

2. You need to export your server,

'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;

3. Write your tests as:

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

simple test case to check if the server is running properly.

const chai = require('chai'),
chaiHttp = require('chai-http'),
server = require('../app'),
faker = require('faker'),
should = chai.should();

chai.use(chaiHttp);

describe('Init', function () {

it('check app status', function (done) {
  chai.request(server).get('/').end((err, res) => {
    should.not.exist(err);
    res.should.have.status(200);
    done();
  })
});

});

Test Cases for get API

describe('/Get API test', function () {

  it('Check the api without user id parameter', function (done) {
    chai.request(server).get('/post-list').end((err, res) => {
      should.not.exist(err);
      res.should.have.status(401);
      res.body.should.be.a('object');
      res.body.should.have.property('message');
      res.body.should.have.property('message').eql('User Id parameter is missing');
      done();
    })
  });

  it('Check the api with user id. Success', function (done) {
    chai.request(server).get('/post-list?user_id=1').end((err, res) => {
      should.not.exist(err);
      res.should.have.status(200);
      res.body.should.be.a('object');
      res.body.should.have.property('userId');
      res.body.should.have.property('title');
      res.body.should.have.property('body');
      done();
    })
  });

});

Test Case for Post API

describe('/POST API test', function () {

  it('Check the api without parameters . failure case', function (done) {
    chai.request(server).post('/submit-data').send({}).end((err, res) => {
      should.not.exist(err);
      res.should.have.status(401);
      res.body.should.be.a('object');
      res.body.should.have.property('message');
      res.body.should.have.property('message').eql('Mandatory params are missing!');
      done();
    })
  });

  it('Check the API with valid parameters. Success', function (done) { 
    chai.request(server).post('/submit-data').send({name:faker.name.firstName(),email:faker.internet.email()}).end((err, res) => { 
      should.not.exist(err);
      res.should.have.status(200);
      res.body.should.be.a('object');
      res.body.should.have.property('message');
      res.body.should.have.property('message').eql('data saved successfully');
      done();
    })
  });

});

Add test cases as per the different case available in your API.

Find here the basic terminologies and complete sample application to proceed: https://medium.com/@pankaj.itdeveloper/basics-about-writing-tests-in-nodejs-api-application-4e17a1677834

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM