【问题标题】:How to get 100% test coverage using reduxsauce如何使用 reduxsauce 获得 100% 的测试覆盖率
【发布时间】:2019-11-06 18:08:44
【问题描述】:

我正在尝试使用 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 行,我没有在声明处理程序 add()remove() 时执行测试。

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

【问题讨论】:

  • 您能否更新您的问题以包含您的测试代码?很难说为什么你的测试没有得到完整的代码覆盖率而没有看到它。与此同时,我的回答 here 谈到了如何测试 reduxsauce 并且可能会有所帮助。
  • 谢谢布赖恩,我会编辑我的问题并添加更多细节。但是,我也找到了解决问题的可能方法。
  • 哥们,我一直在考虑,我不会编辑问题,因为我的问题只要看我写的代码sn-ps就可以解决。好吧,我会回答并希望它足以帮助社区。再次感谢

标签: javascript reactjs redux react-redux jestjs


【解决方案1】:

只要看看这个部分,就会清楚为什么会出现问题(在这种情况下,没有达到分支标准中的 100% 覆盖率)。

/* ... */ add(state = INITIAL_STATE, action) { /* ... */
/* ... */ remove(state = INITIAL_STATE, action) { /* ... */

我们可以这样理解这个语法:

function add ()的声明,有如下条件

  • 如果您在第一个参数中传递一个值,则假定state 将在函数范围内具有此值;
  • 如果未传递值(或者如果传递的值为undefined),则假定state 在函数范围内将值设置为INITIAL_STATE

[阅读有关此语法的更多信息here]

由于声明了这个条件,有必要测试这两种可能性,因为测试在分支标准中具有 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');
  }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2017-02-13
    相关资源
    最近更新 更多