【发布时间】:2017-12-25 20:58:20
【问题描述】:
我正在使用 Jest 在 Node/Express 中为单独的中间件函数编写单元测试。
中间件的简单示例:
function sendSomeStuff(req, res, next) {
try {
const data = {'some-prop':'some-value'};
res.json(data);
next();
} catch (err) {
next(err);
}
}
还有我的测试套件示例:
const httpMocks = require('node-mocks-http');
const { sendSomeStuff } = require('/some/path/to/middleware');
describe('sendSomeStuff', () => {
test('should send some stuff', () => {
const request = httpMocks.createRequest({
method: 'GET',
url: '/some/url'
});
let response = httpMocks.createResponse();
sendSomeStuff(request, response, (err) => {
expect(err).toBeFalsy();
// How to 'capture' what is sent as JSON in the function?
});
});
});
我必须提供一个回调来填充函数中调用的next 参数。通常,这将“找到下一个匹配模式”,并将req 和res 对象传递给该中间件。但是,如何在测试设置中做到这一点?我需要验证响应中的 JSON。
我不想接触中间件本身,它应该包含在测试环境中。
我在这里遗漏了什么吗?
【问题讨论】:
标签: node.js unit-testing express jestjs middleware