什么是嘲笑一个只能与开玩笑在浏览器中运行的获取调用的最简单方法?
如果我正在测试一个函数的函数,并且我在项目中使用的所有获取呼叫都只能在浏览器中运行。我是否仍然需要在节点上安装一些软件包并导入它以模拟该调用?
像这样的简单场景参考:在开玩笑的测试中未定义
未定义:
// fetcKey.js
export async function fetchKey() {
try {
const key = await fetch('http://localhost:3000/key');
return (await key.text());
}
catch(error){
throw error;
}
}
//fetchKey.test.js
import fetchKey from './fetchKey'
test('Checks fetchKey return', () => {
expect(fetchKey()).not.toThrow();
})
If I'm testing a function that makes a fetch call, and all the fetch calls I have in the project are only meant to run in the browser. Do I still need to have some package installed on node and import it to be able to mock that fetch call?
A simple scenario like this throws ReferenceError: fetch is not defined
in the Jest test:
// fetcKey.js
export async function fetchKey() {
try {
const key = await fetch('http://localhost:3000/key');
return (await key.text());
}
catch(error){
throw error;
}
}
//fetchKey.test.js
import fetchKey from './fetchKey'
test('Checks fetchKey return', () => {
expect(fetchKey()).not.toThrow();
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够使用
node> nodefetch
:((请注意,这是一个eCmascript模块,不能用
需要
导入,如其文档中所述)。You should be able to use
node-fetch
:(Note it's an ECMAScript Module and cannot be imported with
require
, as mentioned in their documentation).