我正在尝试测试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和测试的新手。在研究时,我还没有找到一种方法来测试它。任何帮助或指导都将不胜感激。
发布于 2021-11-11 11:48:38
通常,当您编写单元测试时,其想法是隔离地测试每个单元。所以在你的例子中,从saga的角度来看,redirectPos内部的逻辑并不重要,你所需要做的就是用正确的参数调用它。然后,可以专门为redirectPos函数编写另一个测试,用于测试内部结构。
测试当前位置可能会有点棘手,我建议访问有关该主题的其他SO问题,如How to mock window.location.href with Jest + Vuejs?
https://stackoverflow.com/questions/69903535
复制相似问题