我几乎可以肯定这是我的错误,但我花了一整天的时间试图解决,但失败了😞。
我正在尝试配置 Node 上的 fetch-mock 以与 jest 一起使用。我尝试了很多事情,最好的结果是这样的:
https://user-images.githubusercontent.com/824198/50566568-7b49e400-0d22-11e9-884f-89720899de3a.png
我确信我的模拟正在工作,因为如果我将它通过参数传递给“Myclass.query”,它就会完美地工作。
我还确信模拟已到达我的测试文件中,因为模拟函数存在于获取模块中。
但是...所有这些都行不通。
我创建了一个非常简单的小项目来观察这个问题的发生:
https://github.com/cesarjr/test-node-fetch
有人可以帮助我吗?
最佳答案
Jest
在测试过程中需要 node-fetch
时随时使用 __mocks__/node-fetch.js
处的模拟。
问题是 the first thing fetch-mock
does is require node-fetch
.
这意味着在 config
上设置 Request
时未定义 here ,因此在未定义的 Request
上调用 prototype
会导致错误 here .
比我聪明的人可能知道如何在 fetch-mock
需要 node 时强制
在 Jest
需要实际的 node-fetch
-fetchnode-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;
...然后在测试中创建沙箱
并将其传递给您的代码,如下所示:
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
});
});
});
});
关于node.js - 带有 fetch-mock 的 Jest 生成错误 : TypeError: Cannot read property 'prototype' of undefined when using on nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000152/