我提供了一个使用 Express 控制器的工作示例,因为您的代码在某些部分被破坏了。不用担心依赖关系——无论你使用什么框架,原则都是一样的。
controller.js
var express = require('express');
var router = express.Router();
router.get('/example', function(req, res) {
res.send({
message: 'bla bla',
fields: {
request_id: '000',
user_id: '3434324'
}
});
});
module.exports = router;
test.js
'use strict';
const chai = require('chai');
const sinon = require('sinon');
const SinonChai = require('sinon-chai');
var sinonStubPromise = require('sinon-stub-promise');
sinonStubPromise(sinon);
require('sinon-mongoose');
chai.use(SinonChai);
chai.should();
const mockHttp = require('node-mocks-http');
const controller = require('./controller');
context('Test', () => {
beforeEach(() => {
if (!this.sandbox) {
this.sandbox = sinon.sandbox.create();
} else {
this.sandbox.restore();
}
});
it('should pass the test',
(done) => {
// Mocking req and res with node-mocks-http
let req = mockHttp.createRequest({
method: 'GET',
url: '/example'
});
let res = mockHttp.createResponse({
eventEmitter: require('events').EventEmitter
});
// spy on the response status
this.sandbox.spy(res, 'send');
var response_object = {
message: 'bla bla',
fields: {
request_id: '000',
user_id: '3434324'
}
};
res.on('end', function() {
try {
res.send.should.have.been.calledWith(response_object);
done();
} catch (e) {
done(e);
}
});
controller.handle(req, res);
});
});
首先使用第 3 方 HTTP req / res 模拟库来创建有效的请求和响应对象。接下来在响应的send() 方法上设置一个间谍,并附加一个事件侦听器,以便在响应发送时调用。
那么我们不显式调用控制器的服务方法,而是通过路由器发送请求,这样就可以自然地处理了。
最后,在事件侦听器中设置断言,并根据预期对象验证响应主体。
使用这个秘籍,您可以在路由和实现级别验证快乐/悲伤路径。