我正在使用Jest在Node / Express中编写单独的中间件函数的单元测试. 中间件的一个简单示例: function sendSomeStuff(req, res, next) { try { const data = {'some-prop':'some-value'}; res.json(data); next(); } catch
中间件的一个简单示例:
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? }); }); });
我必须提供一个回调来填充下一个参数,该参数在函数中调用.通常,这将“找到下一个匹配模式”,并将req和res对象传递给该中间件.但是,如何在测试设置中执行此操作?我需要从响应中验证JSON.
我不想触摸中间件本身,它应该包含在测试环境中.
我在这里错过了什么吗?
好吧,这比我想象的要容易.我肯定忽视了一些事情.将此留给其他可能与之斗争的人.使用res.send(),res.json()或类似的东西返回数据时,响应对象(来自const response = httpMocks.createResponse();)
本身已更新.可以使用res._getData()收集数据:
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' }); const response = httpMocks.createResponse(); sendSomeStuff(request, response, (err) => { expect(err).toBeFalsy(); }); const { property } = JSON.parse(response._getData()); expect(property).toBe('someValue'); }); }); });