如何在Jest中测试Express中的响应数据

len*_*klb 5 unit-testing middleware node.js express jestjs

我正在使用Jest在Node/Express中编写单独的中间件函数的单元测试.

中间件的一个简单示例:

function sendSomeStuff(req, res, next) {
    try {
        const data = {'some-prop':'some-value'};

        res.json(data);
        next();
    } catch (err) {
        next(err);
    }
}
Run Code Online (Sandbox Code Playgroud)

以及我的测试套件示例:

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?
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

我必须提供一个回调来填充next参数,该参数在函数中调用.通常,这将"找到下一个匹配模式",并将reqres对象传递给该中间件.但是,如何在测试设置中执行此操作?我需要从响应中验证JSON.

我不想触摸中间件本身,它应该包含在测试环境中.

我在这里错过了什么吗?

len*_*klb 10

好吧,这比我想象的要容易.我肯定忽视了一些事情.将此留给其他可能与之斗争的人.

使用或类似的方式返回数据时res.send(),res.json()响应对象(from 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');
        });
    });
});
Run Code Online (Sandbox Code Playgroud)