Jest
使用模拟__mocks__/node-fetch.js
任何时候node-fetch
测试期间需要。
问题是第一件事fetch-mock确实需要node-fetch https://github.com/wheresrhys/fetch-mock/blob/f4c828d78614bb0ae0e7f2e1e2de68623bd3d67b/src/server.js#L1.
这意味着Request
设置时未定义config
here https://github.com/wheresrhys/fetch-mock/blob/f4c828d78614bb0ae0e7f2e1e2de68623bd3d67b/src/server.js#L15,所以调用prototype
关于未定义的Request
导致错误here https://github.com/wheresrhys/fetch-mock/blob/f4c828d78614bb0ae0e7f2e1e2de68623bd3d67b/src/lib/request-utils.js#L38.
比我聪明的人可能知道如何强迫Jest
来要求实际的node-fetch
when fetch-mock
需要node-fetch
在模拟中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;
...然后创建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
});
});
});
});