gpt4 book ai didi

javascript - 开 Jest 不承认 promise 中的 spy 电话

转载 作者:行者123 更新时间:2023-12-05 06:40:25 26 4
gpt4 key购买 nike

我想测试一个在 promise 中调用函数的方法。

article-api.js(简化)

articleMiddleware(next) {
return fetch(articleApiListUrl, { headers, method, body })
.then(() => next({ some: 'data'}));

}

这是article-api.js的简化版本,完整代码可以在这里看到: https://gist.github.com/LukasBombach/7bd9cce28d3a3b905fb8a408b37de3a9

我想看看 next 是否被 { some: 'data'} 调用了。我用 fetch-mock模拟我的获取请求

article-api.spec.js(简体)

describe('article api middleware', () => {

it('creates ARTICLE_SUCCESS when fetching an article has been done', () => {
fetchMock.post('*', { some: 'data' });
return articleMiddleware(next)
.then(expect(next).toBeCalledWith({ some: 'data' }))
.then(() => fetchMock.restore());

});

});

这是 article-api.spec.js 的简化版本,完整代码可以在这里看到: https://gist.github.com/LukasBombach/178f591f516fe13c24fb0a4f02c4676c

我得到的是

Expected mock function to have been last called with: [{ some: 'data' }] But it was not called.

如果你查看两个要点中的完整代码,你会发现我的代码有点不同,那里的错误消息是

expect(received).toBe(expected)

Expected value to be (using ===):
2
Received:
1

这是因为 next(action) 在第一个 gist 的第 17 行中调用了 next (同步),但是 next 在 promise 中永远不会被调用。

最佳答案

这里是只使用"jest": "^24.8.0"的解决方案,不需要使用fetch-mock,可以自己手动mock。

文章-api.js:

const fetch = require('node-fetch');

function articleMiddleware(next) {
const articleApiListUrl = 'https://github.com/mrdulin';
const headers = {};
const method = 'get';
const body = {};

return fetch(articleApiListUrl, { headers, method, body }).then(() => next({ some: 'data' }));
}

exports.articleMiddleware = articleMiddleware;

article-api.spec.js:

jest.mock('node-fetch');

const fetch = require('node-fetch');
const { articleMiddleware } = require('./article-api');

describe('articleMiddleware', () => {
it('t1', async () => {
fetch.mockResolvedValueOnce({});
const next = jest.fn();
await articleMiddleware(next);
expect(fetch).toBeCalledWith('https://github.com/mrdulin', { headers: {}, method: 'get', body: {} });
expect(next).toBeCalledWith({ some: 'data' });
});
});

100% 覆盖率的单元测试结果:

 PASS  src/stackoverflow/42676657/article-api.spec.js
articleMiddleware
✓ t1 (9ms)

----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
article-api.js | 100 | 100 | 100 | 100 | |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.131s

这是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/42676657

关于javascript - 开 Jest 不承认 promise 中的 spy 电话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42676657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com