【发布时间】:2016-09-30 11:34:09
【问题描述】:
我正在使用 Express js 在 Node js 中进行单元测试,我正在使用 mocha 进行测试,我正在使用 sinon 来模拟数据。一切都很好,但我的问题是当我运行测试用例时,如果 it() 包含多个断言并且其中任何一个都失败了,那么 mocha 显示整个 it() 失败了。但我希望通过另一个断言,即使任何一个断言失败。 我不想为每个字段写一个 it()。我的测试代码是
//loading testing dependencies
var request = require('supertest');
var server = require('./app');
var chai = require('chai');
var chaiHttp = require('chai-http');
var sinon = require("sinon");
var should = chai.should();
//configuring chai
chai.use(chaiHttp);
//ORM controller (we need to mock data in it's method)
var rootController = require('./app/controllers/users/users_controller');
//Writing test cases
describe('loading express', function () {
//mock data before each request
before(function(){
//select the method of the ORM controller which you want to mock
sinon.stub(rootController, "get", //get is the method of ORM's customers_controller'
function(req, res, next){
//response object which we are going to mock
var response = {};
response.status = 'success',
response.data = {
userId: '0987654321@ef',
userName:'John'
};
next(response);
});
});
it('responds to /users/getUserData', function testMethod(done) {
//call server file (app.js)
request(server)
//send request to the Express route which you want to test
.get('/users/getUserData?id=0987654321')
//write all expactions here
.expect(200)
.end(function(err, res){
console.log("Generated response is ", res.body);
res.should.have.status(200);
res.body.should.be.a('object');
//res.body.status.should.equal("success");
res.body.data.userId.should.equal("0987654321@ef347389");
res.body.data.userName.should.equal("John");
//done is the callback of mocha framework
done();
});
});
it('responds to /', function testSlash(done) {
request(server)
.get('/')
.expect(200, done);
});
it('404 everything else', function testPath(done) {
request(server)
.get('/foo/bar')
.expect(404, done)
});
});
您可以在这里看到我的 userId 应该失败并且应该传递 userName 但是当我运行此代码时它说 responds to /users/getCustomerData 失败了。而不是 mocha 应该说 userId 字段失败并且 userName 字段通过了。
【问题讨论】:
标签: node.js unit-testing mocha.js sinon chai