异步操作创建者-笑话和Axios-超时-未调用异步回调

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

  • moxios
  • 增加玩笑的超时时间
  • MockAdapter

我目前正在再次尝试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...

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

正在测试的代码:

export cosnt getData= () => {
 return dispatch => {
  dispatch(isFetching())
  return dataApi.retrieveData().then(res => {
   dispatch(updateData(res))
  })
 }
}
andy810404 回答:异步操作创建者-笑话和Axios-超时-未调用异步回调

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

  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。希望对您有所帮助。

本文链接:https://www.f2er.com/3106682.html

大家都在问