繁体   English   中英

在 React 中使用 Redux-Saga/Fetch-mock 测试重定向路由

[英]Testing redirect routes with Redux-Saga/Fetch-mock in React

我正在尝试测试何时在 redux-saga 中发生路由重定向。 除了这个我还没有想出如何测试之外,所有其他测试都通过了。

这是我正在测试的传奇功能......

export function* doFetch({ payload: { id } }) {
  try {
    const station = yield call(stationApi.fetch, id)
    yield put(set(station))
    const allStations = yield call(stationApi.fetch)
    const cashDrawer = yield call(buildCashDrawerState, station, allStations)
    yield put(replaceCashDrawerState(cashDrawer))
    yield call(redirectPos, station)
  } catch (error) {
    yield put(notifyError(
      'Something went wrong during the station fetch. Please try again later',
      { id: 'station' },
    ))
  }
}

这是重定向方法...

const redirectPos = (station) => {
  if (window.location.href.includes('pos') && station.cash_drawer) {
    sagamore.router.redirect('pos')
  } else if (!station.cash_drawer) {
    sagamore.router.redirect('sales/dashboard')
  } else {
    return
  }
}

这是迄今为止的测试......

fdescribe('sagas/station', () => {
  afterEach(() => {
    fetchMock.restore()
  })

  fdescribe('doFetch', () => {
    it('fetches station and cash drawer', () => {
      const id = 1
      const station = {
        id,
        name: 'new name',
        cash_drawer: { location_id: 'location', id: 2 },
      }
      const stations = [
        { id: 10, name: 'Station1', cash_drawer_id: 2 },
        { id: 11, name: 'Station2', cash_drawer_id: 2 },
        // { id: 12, name: 'Station3', cash_drawer_id: 3 },
      ]
      fetchMock.mock(
        `/api/stations/${id}`,
        station,
      )
      fetchMock.mock(
        `/api/stations`,
        { results : stations },
      )
      const saga = doFetch({ payload: { id } })
      let expected
      expected = call(stationApi.fetch, id)
      expect(saga.next().value).toEqual(expected)
      expected = put(set(station))
      expect(saga.next(station).value).toEqual(expected)
      expected = call(stationApi.fetch)
      expect(saga.next().value).toEqual(expected)
      saga.next({ results: stations })
      expected = put(replaceCashDrawerState({ drawer: {...station.cash_drawer, stations: stations} }))
      expect(saga.next({ drawer: {...station.cash_drawer, stations: stations} }).value).toEqual(expected)
      // test redirectPos(...)
      expected = call(redirectPos, station)
      expect(saga.next().value).toEqual(expected)
    })
  })
})

我是 Redux-Saga 和测试的新手。 在研究它时,我一直无法找到一种方法来测试它。 任何帮助或指导将不胜感激。

通常,当您编写单元测试时,其想法是单独测试每个单元。 所以在你的情况下,从传奇的角度来看, redirectPos内部的逻辑并不重要,你需要测试的是它是否被正确的参数调用。 然后,您可以专门为redirectPos函数编写另一个测试来测试内部结构。

测试当前位置可能会有点棘手,我建议访问有关该主题的其他 SO 问题,例如如何使用 Jest + Vuejs 模拟 window.location.href?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM