我几乎可以肯定这是我的错误,但我花了一整天的时间试图解决,但我失败了。
我正在尝试将node上的fetch-mock配置为与jest一起使用。我尝试了很多方法,我得到的最好的结果是:
https://user-images.githubusercontent.com/824198/50566568-7b49e400-0d22-11e9-884f-89720899de3a.png
我确信我的模拟是有效的,因为如果我将它通过参数传递给"Myclass.query“,它就能完美地工作。
我还确信mock正在到达我的测试文件中,因为这个mock函数存在于fetch模块中。
但是..。所有这些都不起作用。
我创建了一个非常简单的小项目来观察这个问题的发生:
https://github.com/cesarjr/test-node-fetch
有谁可以帮我?
发布于 2019-01-04 04:02:08
在测试过程中,只要需要node-fetch,Jest就会在__mocks__/node-fetch.js中使用模拟。
问题是the first thing fetch-mock does is require node-fetch。
这意味着在config here上设置Request时未定义它,因此在未定义的Request上调用prototype会导致错误here。
比我聪明的人可能知道如何强制Jest在模拟node-fetch时强制fetch-mock需要实际的node-fetch,但从我看来这看起来不太可能。
看起来你将不得不删除__mocks__/node-fetch.js中的模拟,并将fetch传递给你的代码,如下所示:
myclass.js
class MyClass {
static query(fetch, sessionId, query) {
const url = 'https://api.foobar.com';
const body = {
sessionId,
query
};
return fetch(url, {
method: 'post',
body: JSON.stringify(body)
})
.then(res => res.json());
}
}
module.exports = MyClass;...then在测试中创建sandbox并将其传递给代码,如下所示:
myclass.test.js
const fetch = require('fetch-mock').sandbox();
const MyClass = require('./myclass');
describe('MyClass', () => {
describe('.query', () => {
it('returns the response', () => {
fetch.mock('*', {'result': {'fulfillment': {'speech': 'The answer'}}});
expect.assertions(1);
return MyClass.query(fetch, '123', 'the question').then((data) => {
expect(data.result.fulfillment.speech).toBe('The answer'); // SUCCESS
});
});
});
});发布于 2019-01-20 00:25:41
我现在已经找到了一种可靠的方法来组合fetch-mock和jest http://www.wheresrhys.co.uk/fetch-mock/#usageusage-with-jest
https://stackoverflow.com/questions/54000152
复制相似问题