在 React 中使用 Redux-Saga/Fetch-mock 测试重定向路由
Posted
技术标签:
【中文标题】在 React 中使用 Redux-Saga/Fetch-mock 测试重定向路由【英文标题】:Testing redirect routes with Redux-Saga/Fetch-mock in React 【发布时间】:2021-12-22 11:27:16 【问题描述】:我正在尝试测试何时在 redux-saga 中发生路由重定向。除了这个我还没有弄清楚如何测试之外,所有其他测试都通过了。
这是我正在测试的 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 和测试新手。在研究它时,我无法找到一种方法来测试它。任何帮助或指导将不胜感激。
【问题讨论】:
【参考方案1】:通常,当您编写单元测试时,想法是单独测试每个单元。因此,在您的情况下,从传奇的角度来看,redirectPos
内部的逻辑并不重要,您只需要测试它是否使用正确的参数调用。然后,您可以专门为 redirectPos
函数编写另一个测试来测试内部结构。
测试当前位置可能有点棘手,我建议访问有关该主题的其他 SO 问题,例如 How to mock window.location.href with Jest + Vuejs?
【讨论】:
以上是关于在 React 中使用 Redux-Saga/Fetch-mock 测试重定向路由的主要内容,如果未能解决你的问题,请参考以下文章
无法在 React Native 应用程序中使用 React.memo