【发布时间】:2021-04-26 10:46:20
【问题描述】:
我有一个非常简单的组件,它依赖于两个 fetch 调用:
<template>
<div>
<div ng-if="this.foo">
{{ foo.name }}
</div>
<div ng-if="this.bar">
{{ bar.address }}
</div>
</div>
</template>
<script>
export default {
name: 'identity-card',
data() {
return {
foo:undefined,
bar:undefined
}
}
created() {
Promise.all([
fetch('http://ul/to/api/foo'),
fetch('http://ul/to/api/bar')
]).then(async (response) => {
this.foo = await response[0].json();
this.bar = await response[1].json();
})
}
}
</script>
我正在尝试使用Jest 测试该组件。
虽然我找到了如何用Jest 模拟Promise,但我找不到同时模拟fetch 响应的方法。
如何在不添加外部库且不重构代码的情况下做到这一点?
【问题讨论】:
-
你的测试代码是什么样的?您可能需要使用异步并按特定顺序执行刷新和滴答,以便获取请求正确解析。
-
我做了文档推荐的原因:
global.fetch = jest.fn(() => Promise.resolve({json: () => Promise.resolve({ rates: {CAD: 1.42 } }),}));但这没什么帮助,因为你不能模拟多个fetches
标签: vue.js vuejs2 jestjs mocking