7ov*_*r21 3 testing redux-saga
我有一个传奇,目前有一个yield all(...),我正在尝试找出如何测试以查看我实际上正在使用all()正确的函数进行调用。这是我正在使用的内容的精简版本:
function* start() {\n // I\'d prefer not to start the status polling and the listening for\n // the cancellation until after the request has been submitted, but\n // I\'m having trouble figuring out how to do that. So I\'m just going\n // to listen for \'em all up front here until I\'m smarter.\n yield all([\n waitForCreateRequest(),\n waitForPollStatus(),\n waitForCancelRequest(),\n ])\n}\n\nfunction* waitForCreateRequest() {\n while ( true ) { \n try {\n const { payload } = yield take(\'CREATE_REQUEST\')\n // ...\n } catch ( error ) {\n // ...\n }\n }\n}\n\nfunction* waitForPollStatus() {\n while ( true ) { \n try {\n const { payload } = yield take(\'POLL_STATUS\')\n // ...\n } catch ( error ) {\n // ...\n }\n }\n}\n\nfunction* waitForCancelRequest() {\n while ( true ) { \n try {\n yield take(\'CANCEL_REQUEST\')\n // ...\n } catch ( error ) {\n // ...\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我编写的测试(使用 Mocha 和bdd-lazy-var)是这样的:
describe(\'MySaga\', () => {\n describe(\'*start()\', () => {\n subject(start())\n\n it(\'calls `all()` with the correct functions\', () => {\n expect($subject.next().value).to.eql(all([\n waitForSubmitExportRequest(),\n waitForPollExportStatus(),\n waitForCancelExportRequest(),\n ]))\n })\n })\n})\nRun Code Online (Sandbox Code Playgroud)\n\n没有输出——它只是挂起......然后我收到“JavaScript 堆内存不足”错误。
\n\n如果我console.log($subject.next().value)改为:
describe(\'MySaga\', () => {\n describe(\'*start()\', () => {\n subject(start())\n\n it.only(\'foo\', () => {\n console.log($subject.next().value)\n })\n })\n})\nRun Code Online (Sandbox Code Playgroud)\n\n这就是我得到的:
\n\n MySaga\n *start()\n{ \'@@redux-saga/IO\': true,\n ALL: \n [ GeneratorFunctionPrototype { _invoke: [Function: invoke] },\n GeneratorFunctionPrototype { _invoke: [Function: invoke] },\n GeneratorFunctionPrototype { _invoke: [Function: invoke] } ] }\n \xe2\x9c\x93 foo\nRun Code Online (Sandbox Code Playgroud)\n\n所以我不确定这里发生了什么。
\n\n无数的谷歌搜索并没有真正找到任何有用的东西,而且我发现的最接近的SO帖子(how to test redux-saga alleffect using jest)也没有帮助。
\nstart您的函数不是生成器函数,这是一个拼写错误吗?
反正。你能尝试start像这样重写你的函数吗:
function* start() {
yield all([
call(waitForCreateRequest),
call(waitForPollStatus),
call(waitForCancelRequest),
])
}
Run Code Online (Sandbox Code Playgroud)
现在您的测试可能如下所示:
it('calls `all()` with the correct functions', () => {
expect($subject.next().value).to.eql(all([
call(waitForSubmitExportRequest),
call(waitForPollExportStatus),
call(waitForCancelExportRequest),
]))
})
Run Code Online (Sandbox Code Playgroud)