0
我正在使用Express js在Node js中进行单元测试,并且为了测试我正在使用mocha和模拟我使用sinon的数据。一切都很好,但我的问题是,当我运行测试用例如果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: '[email protected]',
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("[email protected]");
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)
});
});
您可以在这里看到我的用户id应该失败和用户名应传递,但是当我运行这段代码它说,响应/用户/ getCustomerData得到了失败。而不是它摩卡应该说,userId字段失败,并且userName字段已通过。
你的意思是我需要写一个它()的每个字段?还有其他选择吗? –
如果你想看到单独的测试失败或传递,那么它们应该被分成单独的'it()'。没有办法绕过它AFAIK。 – robertklep