node.js - 如何在 JEST 测试用例中检查全局获取的响应

标签 node.js reactjs express jestjs

因此,我正在使用 jest 来测试我的 Node 函数,该函数调用 fetch() APi 来获取数据,现在当我为其编写测试用例时,我收到如下错误:

expect(received).resolves.toEqual()

    Matcher error: received value must be a promise

    Received has type:  function
    Received has value: [Function mockConstructor]

我的功能:

 export function dataHandler (req, res, next) {
    const url= "someURL"
    if (url ) {
        return fetch(url )
            .then((response) => response.json())
            .then((response) => {
                if (response.data) {
                    console.log(response);
                    res.redirect(somewhere`);
                } else {
                    throw Error(response.statusText);
                }
            })
            .catch((error) => {
                next(error);
            });
    } 
}

测试用例:

 it('check if fetch returning the response', async () => {
        // Setup
        const req = jest.fn(),
            res = { redirect: jest.fn() },
            next = jest.fn();
        global.fetch = jest.fn().mockImplementation(() => {
            return new Promise((resolve) =>
                resolve({
                    json: () => {
                        return { data: "hello"};
                    }
                })
            );
        });
        await middlewares.dataHandler(req, res, next);
        //  Assert      
        expect(global.fetch).resolves.toEqual({ data: "hello" });
    });

请注意,我没有使用任何模拟 API,并且也不希望这样做。

谁能帮我解决问题吗?

最佳答案

.resolves只能与 Promise 一起使用.

global.fetch是一个函数,所以 Jest抛出错误。

如果您试图断言 Promise通过调用 global.fetch 返回解析为 json 的对象返回 { data: 'hello' } 的函数那么你可以这样做:

expect((await global.fetch()).json()).toEqual({ data: 'hello' });  // Success!

...但我怀疑你真的想验证 response.data存在并且res.redirect被调用 'somewhere'在这种情况下,你的断言应该是这样的:

expect(res.redirect).toHaveBeenCalledWith('somewhere');  // Success!

关于node.js - 如何在 JEST 测试用例中检查全局获取的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56355434/

相关文章:

javascript - JSON.parse node.js 中的意外结果

mysql - 将 'crypto'模块生成的哈希值保存到mysql

reactjs - Eslint 提示 this.props.handleSubmit 在 prop 验证中丢失

reactjs - 当后端托管在 Azure 上时,create-react-app 代理请求失败并显示 404

javascript - 如何使机器人状态显示为 "Online from Mobile"

reactjs - 使用 React 呈现来自 Express 的 flash 消息

node.js - GraphQL Apollo 中的多对多关系

javascript - Mongoose 设计模型中的嵌入式文档与引用?

node.js - 查找和更新记录 - Mongoose

node.js - 打开端口 3000 EC2 亚马逊网络服务