简体   繁体   English

使用 Mocha 和 Express Rest API 进行单元测试

[英]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.到目前为止,我能够运行简单的测试,比如“添加两个数字并测试它们是否大于 0”,但我想使用 TDD 构建一个 REST API。 So far I have this:到目前为止,我有这个:

My routes/index.js file:我的routes/index.js文件:

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:我的index.test.js文件:

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.那是我学习 TDD 的第一天,所以如果你看到任何愚蠢的东西,请告诉我。

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同样在你的终端输入npm i supertest --save-dev

1. Install the dev dependencies for mocha 1. 安装 mocha 的开发依赖

  • chai : assertion library for node and browser, chai :节点和浏览器的断言库,
  • chai-http : HTTP Response assertions for the Chai Assertion Library. chai-http : Chai 断言库的 HTTP 响应断言。

2. You need to export your server, 2. 你需要导出你的服务器,

'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: 3. 将您的测试编写为:

If your test script is users.spec.js ,it should start by:如果你的测试脚本是users.spec.js ,它应该从:

 // 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你可以看看我的仓库, 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 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 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.根据 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在这里找到基本术语和完整的示例应用程序以继续: https : //medium.com/@pankaj.itdeveloper/basics-about-writing-tests-in-nodejs-api-application-4e17a1677834

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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