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

时间:2019-06-24 23:05:57

标签: javascript reactjs redux react-redux jestjs

我正在尝试使用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,但是我不知道如何测试这部分方法以允许测试覆盖率标准

1 个答案:

答案 0 :(得分:0)

只需看一下本节,就会清楚为什么会出现问题(在这种情况下,未达到Branchs准则中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');
  }
);
相关问题