我们如何模拟Redux异步操作的fetch

How do we mock fetch for Redux Async Actions?

本文关键字:Redux 异步操作 fetch 模拟 何模拟 我们      更新时间:2023-09-26

在Redux的写入测试部分,如果store.dispatch实际上在调用actions.fetchTodosstore.dispatch(actions.fetchTodos())如何不调用fetch方法?

it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', (done) => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { todos: ['do something'] })
    const expectedActions = [
      { type: types.FETCH_TODOS_REQUEST },
      { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
    ]
    const store = mockStore({ todos: [] }, expectedActions, done)
    store.dispatch(actions.fetchTodos())
})

它正在调用fetch方法,但nock行:

nock('http://example.com/')
  .get('/todos')
  .reply(200, { todos: ['do something'] })

截取HTTP请求,以便fetch简单地返回正确的数据(而不实际到达端点)。

另一种选择是将对fetch的调用提取到另一个模块(比如api)中,并在动作创建者中使用它。在测试中,您只需在api模块上模拟出适当的方法。