【问题标题】:Async Action Creator - Jest and Axios - Timeout - Async callback was not invokedAsync Action Creator - Jest 和 Axios - Timeout - 未调用异步回调
【发布时间】:2020-03-09 18:25:04
【问题描述】:

我正在为我的异步操作创建者编写测试,但是当我的测试运行时出现超时错误。我试过了

  • 莫西奥斯
  • 增加笑话超时
  • 模拟适配器

我目前正在再次尝试 Moxios。

myTest(已编辑以反映更改):

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import moxios from 'moxios'
import * as actions from './actions'
import mockData from './mockData'

const middleware = [thunk]
const mockStore = configMockStore(middleware)

describe('action tests: ', () => {
 beforeEach(function() {
  moxios.install()
 }

 afterEach(function() {
  moxios.uninstall()
 }

 it('should get data', async done => {
  moxios.stubRequest('/data/*', { status: 201, response: mockData })

  const expectedActions = [{ type: actions.dataActions.RECEIVED_DATA }]

  const store = mockStore({ data: [] })

  await store.dispatch(actions.getData()).then(() => { 
   expect(store.getActions()).toEqual(expectedActions)
  })
  done();
 }, 10000)
})

我得到的错误是:Timeout - Async callback was not invoked within the 10000ms timeout...

通过查看我的代码和覆盖率,我可以看到 promise 没有被使用,因为 .then() 部分没有根据我的代码覆盖率执行。那么我的测试用例做错了吗?我开玩笑地查看了其他人对 Axios 的实现,但我总是收到这个超时错误。

正在测试的代码:

export cosnt getData= () => {
 return dispatch => {
  dispatch(isFetching())
  return dataApi.retrieveData().then(res => {
   dispatch(updateData(res))
  })
 }
}

【问题讨论】:

  • 你能发布你正在测试的代码,以便我们看看出了什么问题
  • @RedBaron,我添加了正在测试的代码。我也应该添加 API 函数吗?它是 axios 的标准 GET

标签: reactjs unit-testing react-redux jestjs axios


【解决方案1】:

我注意到有两件事可能导致此错误:

  1. url 通配符在stubRequest 中不起作用,您应该指定部分或全部 uri(为外部 api 端点添加主机名)。

    例如moxios.stubRequest('/data/*', { status: 201, response: mockData })

  2. resolves 不应该在那里,因为上面的.then 已经得到了承诺。 更新后应该是:

    expect(store.getActions()).toEqual(expectedActions)

我有一个类似于这个测试用例的沙箱: https://codesandbox.io/s/react-and-redux-thunk-49696

您可以参考文件redux.spec.js。希望对您有所帮助。

【讨论】:

  • 感谢您的回复!我已将 stubRequest 网址更改为类似于您的示例,并在 expect 之后删除了 .resolves 调用,但我仍然遇到同样的问题。
  • 你是否使用axios在'retrieveData'函数中命中端点,因为moxios只能模拟axios请求。如果通配符有效,请尝试在 stubRequest 中使用完整的 uri。
  • 感谢您的帮助。我最终切换到 fetch,因为我尝试使用 Axios 的所有方法都不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
  • 2020-08-17
  • 1970-01-01
  • 2018-04-29
  • 2019-07-05
  • 2019-12-05
  • 2018-09-18
相关资源
最近更新 更多