【问题标题】:How to test response data from Express in Jest如何在 Jest 中测试 Express 的响应数据
【发布时间】: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 参数。通常,这将“找到下一个匹配模式”,并将reqres 对象传递给该中间件。但是,如何在测试设置中做到这一点?我需要验证响应中的 JSON。

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

我在这里遗漏了什么吗?

【问题讨论】:

    标签: node.js unit-testing express jestjs middleware


    【解决方案1】:

    找到了解决办法! 把这个留给其他可能会遇到同样问题的人。

    当使用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');
            });
        });
    });
    

    【讨论】:

    • 如果它解决了您的问题,也将您的答案标记为正确!
    • 这个需要贴在广告牌上,周围有霓虹灯,我从高处到低处找,直到找到这个。
    【解决方案2】:

    我使用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 } 
      })),
    }));
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-02
      • 2021-10-23
      • 2019-06-16
      • 2020-05-17
      • 2019-01-08
      • 2020-07-14
      • 2019-11-04
      • 2019-08-01
      相关资源
      最近更新 更多