vue.js - VueJS/开 Jest : Mocking multiple fetch responses

标签 vue.js vuejs2 jestjs mocking

我有一个非常简单的组件,它依赖于两个 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 设置为使用 mockReturnValueOnce() APIjest.fn()对于每个预期的 fetch 调用:

const makeFetchResp = value => ({ json: async() => value })   // mock fetch().json()
const mockFetch = jest.fn()
                   .mockReturnValueOnce(makeFetchResp(true))  // 1st fetch() returns true
                   .mockReturnValueOnce(makeFetchResp(false)) // 2nd fetch() returns false
global.fetch = mockFetch

在断言来自 fetch 的任何更改之前,测试需要刷新它们的 Promise 以调用它们的 then 回调。这可以通过以下方式完成:

const flushPromises = () => new Promise(r => setTimeout(r))
await flushPromises()

您的测试看起来与此类似:

it('fetches foo bar', async () => {
  const makeFetchResponse = value => ({ json: async() => value })
  const mockFetch = jest.fn()
    .mockReturnValueOnce(makeFetchResponse(true))
    .mockReturnValueOnce(makeFetchResponse(false))
  global.fetch = mockFetch

  const wrapper = shallowMount(MyComponent)

  await flushPromises()

  expect(mockFetch).toHaveBeenCalledTimes(2)
  expect(wrapper.vm.foo).toBeTruthy()
  expect(wrapper.vm.bar).toBeFalsy()
})

关于vue.js - VueJS/开 Jest : Mocking multiple fetch responses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65837171/

相关文章:

vue.js - Codesandbox 中带有 vuetify 的 vue-cli 出现故障

vue.js - 构建 Vue.js 应用程序时 JavaScript 堆内存不足

typescript - 带有 webpack 别名的 Vue-typescript 错误,找不到路径

Vue.js:防止用户在使用 Vue <transition> 转换元素时单击元素

vue.js - 具有动态列的元素 UI 表格

vue.js - 如果最后一项不是 Vue 路由,如何为 router.back() 提供替代方案?

vue.js - Element Ui + Vue JS [列偏移不起作用]

javascript - React 和 jest 模拟模块

typescript - Jest 在没有 webpack 的情况下配置 typescript

javascript - 在 Angular Jest 测试中模拟窗口、文档和鼠标单击事件属性