unit test for redux toolkit prepare callback function

huangapple go评论55阅读模式
英文:

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,
    });
  });

  ...
});

huangapple
  • 本文由 发表于 2023年6月29日 11:31:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76577898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定