我想知道是否有人有关于如何对以下redux-saga登录/注销流进行单元测试的任何提示:
let pollingTask = null
function * handleLogin () {
try {
const token = yield call(loginHandler)
pollingTask = yield fork(handlePolls, token)
yield put('LOGIN_SUCCSES')
} catch (e) {
yield put('LOGIN_FAILURE')
}
}
function * handlePolls (token) {
while (true) {
try {
yield call(pollHandler, token)
yield put('POLL_SUCCESS')
} catch (e) {
yield put('POLL_FAILURE')
} finally {
if (yield cancelled()) {
yield call(pollCancelled)
}
}
}
}
function * handleLogout () {
try {
yield call(logoutHandler)
yield cancel(pollingTask)
yield put('LOGOUT_SUCCESS')
} catch (e) {
yield put('LOGOUT_FAILURE')
}
}
由于我需要在注销时取消pollingTask
,我尝试在我的测试中使用createMockTask()但是当我调用undefined
传奇时,我总是将其值设为handleLogout()
虽然我知道我的handleLogin()
将始终首先启动,但它会初始化pollingTask
。
非常感谢任何帮助!
答案 0 :(得分:0)
要使函数转到yield cancel(),请在迭代器上调用.return()。
一个例子 -
//assuming this saga
function* saga() {
try {
const resp = yield call(someApi)
yield put(action(resp))
} finally {
if(yield cancelled()) {
// handle logic specific to cancellation. For example
yield <some effect>
}
}
}
// test
const gen = saga()
expect(gen.next().value).toEqual(call(someApi))
// simulates cancellation
// gen asking for cancel status
expect(gen.return().value).toEqual( cancelled() )
// answer yes, we've been cancelled
expect(gen.next(true).value).toEqual(<some effect>)
取自https://github.com/redux-saga/redux-saga/issues/266#issuecomment-216087030
的示例