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

How to test response data from Express in Jest

我正在使用 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 参数。通常,这会 'find the next matching pattern',并将 reqres 对象传递给该中间件。但是,如何在测试设置中执行此操作?我需要从响应中验证 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');
        });
    });
});

我通过使用 jest.fn() 做了不同的方式。例如: 如果你想测试 res.json({ status: YOUR_RETURNED_STATUS }).status(200);

const res = {};
res.json = jest.fn(resObj => ({
    status: jest.fn(status => ({ res: { ...resObj, statusCode: status } 
  })),
}));

基本上,我模拟了资源链方法(jsonstatus)。

如果您的响应结构是这样的话,您可以这样做 expect(YOUR_TEST_FUNCTION_CALL).toEqual({ res: { status: 'successful', statusCode: 200 }});