【问题标题】:Type error when testing async action creator, I don't understand the difference between the creator and the unit mock测试异步动作创建者时输入错误,我不明白创建者和单元模拟之间的区别
【发布时间】:2021-07-13 16:53:13
【问题描述】:

所以我有一个创建对 openWeather 网站的 API 调用的动作创建者,我想测试这个创建者,但是在设置模拟测试时,存储和 thunk;我收到一个我不确定的类型错误。

我的动作创建者:

type Effect = ThunkAction<void, State, unknown, WeatherActions>

export const fetchWeatherData = (city: string): Effect => async (dispatch) => {
  try {
    return await axios.get(`${URL}${city}&appid=${API}`)
      .then((resp) => {
        console.log('res', resp)
        dispatch(weatherSuccess(resp.data))
      })
      .catch((err) => {
        console.log('err', err)
        dispatch(loadingError(err))
      })
  }
  catch(e) {
    throw Error(`Network Error: ${e}`)
  }
}

我的动作创建者测试设置:

jest.mock('axios')

const initialState = {}
type State = typeof initialState

const middleware = [thunk]
const mockStore = configureStore<State, ThunkDispatch<State, unknown, AnyAction>>(middleware)
const store = mockStore(initialState)

describe('Testing api action creator', () => {
  afterEach(() => {
    store.clearActions()
  })

  it('#loading', async () => {
    await store.dispatch(fetchWeatherData('peterborough'))
  })

})

这是与上述语句中的 'fetchWeatherData('peterborough')' 对齐的错误:

【问题讨论】:

    标签: reactjs typescript react-redux redux-thunk react-typescript


    【解决方案1】:

    我设法通过为 store 提供正确的状态类型来修复此错误,我的状态不是空对象,而是作为 reducer 中的初始状态赋予 store 的显式类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 2017-12-09
      • 2018-04-27
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      相关资源
      最近更新 更多