英文:
unit test for redux toolkit prepare callback function
问题
Istanbul 显示 prepare
函数没有被覆盖。您知道如何覆盖它吗?提前感谢您。
尝试搜索 Redux Toolkit 文档,但未找到相关信息。
英文:
My code
addTodo: {
reducer: (state: State, action: { payload: Record<string, string>; type: string }) => {
state.todoMessage = action.payload.todoMessage;
state.id = action.payload.id;
state.completed = action.payload.completed;
},
prepare: (todoMessage: string) => {
return {
payload: { message: todoMessage, id: uuid(), completed: false }
};
}
},
and my unit test:
const action = {
type: addTodo.type,
payload: {
message: 'buy milk',
id: 'id',
completed: false,
},
};
const state = productDetailsReducer(reducerState, action);
expect(state.todoMessage).toEqual('buy milk');
expect(state.id).toEqual('id');
expect(state.completed).toBeFalsy();
my question is that istanbul shows prepare
function is not covered.
Any idea how to cover it? thanks in advance
Tried to search the redux toolkit document, cannot find anything around it
答案1
得分: 1
你应该在单元测试中调用addTodo
动作,以便覆盖其代码。模拟uuid
以返回确定性ID值。
示例:
// 这里假设使用uuid npm包,请根据您的特定情况进行调整
jest.mock('uuid', () => ({
v4: jest.fn(() => '12345'),
}));
...
describe("todo slice", () => {
...
it("应该添加待办事项", () => {
const action = addTodo("购买牛奶");
const state = productDetailsReducer(reducerState, action);
expect(state).toEqual({
todoMessage: "购买牛奶",
id: "12345",
completed: false,
});
});
...
});
英文:
You should call the addTodo
action in the unit test so you get coverage over its code. Mock uuid
to return determinant id value.
Example:
// I'm assuming uuid npm package here, tweak for your specific use case
jest.mock('uuid', () => ({
v4: jest.fn(() => '12345'),
}));
...
describe("todo slice", () => {
...
it("should add todo", () => {
const action = addTodo("buy milk");
const state = productDetailsReducer(reducerState, action);
expect(state).toEqual({
todoMessage: "buy milk",
id: "12345",
completed: false,
});
});
...
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论