【发布时间】:2018-06-10 12:27:26
【问题描述】:
react、react-redux/saga 和 jest 中的新功能
考虑:
-----组件()----
componentDidMount() {
this.props.actions.initTodos(
axios,
ajaxURLConstants.WP_GET_TODOS,
appStateActions.setAppInIdle,
appStateActions.setAppInProcessing,
todosActions.todosInitialized
);
}
所以当我的 TodoApp 组件确实挂载时,它会调度 INIT_TODOS 操作,然后 我的根传奇正在侦听,并且当它捕获时它会产生相应的工人传奇以采取相应的行动。
-----对应的工人传奇-----
export function* initTodosSaga( action ) {
try {
yield put( action.setAppInProcessing() );
let response = yield call( action.axios.get , action.WP_GET_TODOS );
if ( response.data.status === "success" )
yield put( action.todosInitialized( response.data.todos ) );
else {
console.log( response );
alert( response.data.error_msg );
}
} catch ( error ) {
console.log( "error" , error );
alert( "Failed to load initial data" );
}
yield put( action.setAppInIdle() );
}
-----到目前为止的测试-----
import todos from "../../__fixtures__/todos";
import { initTodosSaga } from "../todosSaga";
test( "saga test" , () => {
let response = {
status : "success",
todos
},
action = {
axios : {
get : function() {
return new Promise( ( resolve , reject ) => {
resolve( response );
} );
}
},
WP_GET_TODOS : "dummy url",
setAppInIdle : jest.fn(),
setAppInProcessing : jest.fn(),
todosInitialized : jest.fn()
};
let initTodosSagaGen = initTodosSaga( action );
initTodosSagaGen.next();
expect( action.setAppInIdle ).toHaveBeenCalled();
} );
-----测试结果-----
所以重要的部分是这个
console.error node_modules\redux-saga\lib\internal\utils.js:240
在检查 put(action) 时未捕获:参数操作未定义
但我有 console.log 我在 worker saga 中通过测试的操作,实际上它不是未定义的
我错过了什么?
提前致谢。
---------更新------------
好的,请注意,它在这行代码上抱怨
yield put( action.setAppInIdle() );
在 try catch 块之外,所以我做了一些更改
1.) 我将上面的代码移到 try catch 块中,就在
的 else 语句之后if ( response.data.status === "success" )
请检查上面的initTodosSaga代码
然后在我的传奇测试中,我测试
expect( action.setAppInProcessing ).toHaveBeenCalled();
而不是 setAppInIdle 间谍功能
这是测试结果
所以测试通过了! 但它仍然在抱怨操作未定义
现在有趣的是,如果在我的传奇测试中,如果我现在测试这个
expect( action.setAppInProcessing ).toHaveBeenCalled();
expect( action.setAppInIdle ).toHaveBeenCalled();
这是结果
所以现在它仍然抱怨动作仍未定义(我的屏幕截图中没有包含,但仍然与上面相同)
加上我关于 setAppInIdle 间谍函数的第二个断言没有被调用,但 setAppInProcessing 确实通过了!
我希望这些附加信息有助于解决这个问题。
【问题讨论】:
-
错误不在 initTodosSaga 中,它在 deleteTodoSaga 中,您能否编辑您的问题以包含该 saga 的代码和相应的测试,请?
-
@PatrickHund 好的问题已编辑,我不确定为什么 deleteTodoSaga 在这里被开玩笑抱怨,因为我还没有为那个传奇创建测试。此外,deleteTodoSaga 还没有重构,我计划将所有内容传递给动作有效负载,以便轻松测试 saga,因为 saga 所需的几乎所有内容都已经在动作中(依赖注入),因此,我做了什么initTodosSaga.
-
@PatrickHund 我已经编辑了问题,我只是替换了上面的图像截图。我已经注释掉了除了 initTodosSaga 之外的所有其他工人 sagas(及其用法)以避免混淆。屏幕截图现在显示它在 initTodosSaga 中抱怨。我重新运行了测试,确实它仍然抱怨动作未定义,现在在 initTodosSaga
-
好的,我现在就afk,希望以后可以看看
-
非常感谢,非常感谢,非常渴望学习。朋友节日快乐。
标签: reactjs testing jestjs redux-saga