【发布时间】:2017-04-07 19:50:21
【问题描述】:
我正在自学如何使用redux-saga,同时自学单元测试,特别是 Jest。我从 redux-saga 的文档中获取了一个示例 saga,在这里:
http://yelouafi.github.io/redux-saga/docs/advanced/NonBlockingCalls.html
...并出于我自己的目的对其进行了修改。它应该是一个简单的身份验证处理程序,它侦听登录或注销操作(因为该函数不知道用户是否已登录),然后采取适当的行动。我已经在应用程序中测试了该功能,它似乎按预期运行,这很棒。函数如下:
function* authFlow() {
while (true) {
const initialAction = yield take (['LOGIN', 'LOGOUT']);
if (initialAction.type === 'LOGIN') {
const { username, password } = initialAction.payload;
const authTask = yield fork(
authorizeWithRemoteServer,
{ username: username, password: password }
);
const action = yield take(['LOGOUT', 'LOGIN_FAIL']);
if (action.type === 'LOGOUT') {
yield cancel(authTask);
yield call (unauthorizeWithRemoteServer)
}
} else {
yield call (unauthorizeWithRemoteServer)
}
}
}
这看起来相当简单,但我很难测试它。以下是我的基于 Jest 的测试脚本的注释版本:
it ('authFlow() should work with successful login and then successful logout', () => {
const mockCredentials = {
username: 'User',
password: 'goodpassword'
};
testSaga( stateAuth.watcher )
// This should test the first 'yield', which is
// waiting for LOGIN or LOGOUT. It works
.next()
.take(['LOGIN', 'LOGOUT'])
// This should test 'authorizeWithRemoteServer',
// and appears to do that properly
.next({
type: 'LOGIN',
payload: mockCredentials
})
.fork(
stateAuth.authorizeWithRemoteServer,
mockCredentials)
// This should reflect 'yield take' after the 'yield fork',
// and does so
.next()
.take(['LOGOUT', 'LOGIN_FAIL'])
/*
This is where I don't understand what's happening.
What I would think I should do is something like this,
if I want to test the logout path:
.next({ type: 'LOGOUT' })
.cancel(createMockTask())
...but that results in the following, perhaps predictable, error:
cancel(task): argument task is undefined
What I found does make the test not fail is the following line, but
I do not understand why it works. The fact that it matches
"take(['LOGIN', 'LOGOUT'])" indicates that it has
looped back to the top of the generator
*/
.next(createMockTask())
.take(['LOGIN', 'LOGOUT'])
})
所以要么我做错了 sagas,要么我不明白如何测试 sagas,或者测试这种 sagas 真的很难而且可能不切实际。
那么这里发生了什么?提前致谢!
【问题讨论】:
标签: unit-testing redux jestjs redux-saga redux-saga-test-plan