如何使用 reduxsauce 获得 100% 的测试覆盖率

我正在尝试使用 Jest 使用Redux ( react-redux+ reduxsauce)测试 React 应用程序。我实施了以下方法:


import { createActions, createReducer } from "reduxsauce";


/**

* Action types & creators

*/

export const { Types, Creators } = createActions({

    addSample: ["text"],

    removeSample: ["id"]

});


/**

* Handlers

*/

export const INITIAL_STATE = [];

export function add(state = INITIAL_STATE, action) {

    return [...state, { id: Math.random(), text: action.text }];

}

export function remove(state = INITIAL_STATE, action) {

    return state.filter(sample => sample.id !== action.id);

}


/**

* Reducer

*/

export default createReducer(INITIAL_STATE, {

    [Types.ADD_SAMPLE]: add,

    [Types.REMOVE_SAMPLE]: remove

});

这个实现允许我在组件之间使用 Redux 存储。但是,在测试中我无法达到 100% 的覆盖率,因为仅在分支的标准中我是覆盖率 0%(在其他标准中我达到 100% - 语句、函数、行);在 Coverage 的反馈中指出,在第 16 行和第 20 行,我没有对 Handlersadd()和remove().


我想在内部reduxsauce实现了一些 Reducer switch case,但我不知道如何测试这部分方式允许测试覆盖标准


HUH函数
浏览 223回答 1
1回答

富国沪深

只要看看这一节,就会清楚为什么会出现问题(在这种情况下,分支标准中没有达到 100% 的覆盖率)。/* ... */ add(state = INITIAL_STATE, action) { /* ... *//* ... */ remove(state = INITIAL_STATE, action) { /* ... */我们可以按如下方式阅读此语法:, 的声明function add ()具有以下条件如果你在第一个参数中传递一个值,假设state在函数作用域中会有这个值;如果没有传递一个值(或者如果这个传递的值为undefined),则假设state将INITIAL_STATE在函数作用域中设置为该值;[在此处阅读有关此语法的更多信息]由于此条件已声明,因此有必要测试两种可能性,以便测试在分支标准中具有 100% 的覆盖率。例如:it("should return INITIAL_STATE when passed undefined on parameter and sometingh on action", () => {    expect(setCurrent(undefined, action)).toBe(INITIAL_STATE); });it("should return 'test' when passed 'test' on parameter and sometingh on action",   () => {    expect(setCurrent("test", action)).toBe('test');  });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript