【问题标题】:Branch Coverage for Redux reducerRedux reducer 的分支覆盖率
【发布时间】:2017-06-27 11:17:11
【问题描述】:

假设我有以下减速器:

import {FOO} from '../const/Foo'

const myReducer = (initialState = {foo: ''}, action) => {
  const state = {}
  if (action) {
    switch (action.type) {
      case FOO:
        state.foo = action.foo
    };
  }
  return Object.assign({}, initialState, state)
}

我用 jest 进行测试:

import FOO from '../const/Foo'

test('returns correct state when action is not "Foo"', () => {
  expect(myReducer({foo: 'bar'}, {type: 'foo'})).toEqual({foo: 'bar'})
})

test("returns correct state when action is 'Foo'", () => {
  expect(myReducer({}, {type: FOO, foo: 'bar'})).toEqual({foo: 'bar'})
})

test('when there is no action / testing the default', () => {
  expect(myReducer()).toEqual({foo: ''})
})

这会产生4/5 的分支覆盖率。经过一些思考/删除和/或重新添加行后,我已经到达了initialState 集上的分支逻辑。这几乎是有道理的。除了:

1) 为什么最后一个测试,一个空的myReducer() 呼叫没有涵盖这种情况。

当reducer被缩减为:

const myReducer = (initialState = {foo: ''}, action) => {
    const state = {}
    return Object.assign({}, initialState, state)
}

测试(现在失败)的分支覆盖率为 1/1。

这是怎么回事?

编辑:根据要求,我正在添加配置。我将以下 jest.json 传递给 jest:

{

  "bail": true,
  "verbose": true,
  "moduleNameMapper": {
    "\\.(sass|jpg|png)$": "<rootDir>/src/main/js/config/emptyExport.js"
  },
  "testRegex": ".*(?<!snapshot)\\.(test|spec)\\.js$",
  "collectCoverage": true,
  "collectCoverageFrom": ["src/main/js/**/*.js"
    , "!**/node_modules/**"
    , "!**/*spec.js"
    , "!src/main/js/config/emptyExport.js"
    , "!**/coverage/**/*.js"
    , "!src/main/js/app.js"
    , "!src/main/js/store/configureStore.js"
    , "!src/main/js/reducers/index.js"],
  "coverageDirectory": "<rootDir>/src/main/js/coverage",
  "coverageThreshold": {
    "global": {
      "branches": 85,
      "function": 95,
      "lines": 95,
      "statements": 95
    }
  }
}

编辑2: 以下测试也不影响测试覆盖率:

test('when there is no action / testing the default', () => {
  expect(addressReducer(undefined, {foo: 'bar'})).toEqual({address: ''})
})

我仍然不明白为什么最初的默认测试实现从分支覆盖率的角度来看是不等价的。

【问题讨论】:

  • 您在使用 Jest 的内置覆盖功能吗?您的构建和测试运行设置是什么?对我来说,我使用 Jest 的内置覆盖功能获得了 100% 的覆盖率(分支、语句、函数和行)。
  • 请同时发布您的配置,您发布的代码具有 100% 的代码覆盖率,也适用于分支机构
  • 我已经添加了 jest 配置。还对减速器做了细微的改动,更符合实际使用情况。我没有直接使用“FOO”,而是将 FOO 作为常量导入。

标签: javascript ecmascript-6 redux code-coverage jestjs


【解决方案1】:

myReducer() 的最后一个测试涵盖了应用 initialState 的默认值(在您的情况下为 {foo: ''})的情况。

【讨论】:

    【解决方案2】:

    我认为缺少的是您没有对selectdefault 分支进行测试。你需要添加

    test('returns correct state when action type is "Bar"', () => {
      expect(myReducer({foo: ''}, {type: 'bar'})).toEqual({foo: ''})
    })
    

    【讨论】:

      猜你喜欢
      • 2012-01-11
      • 2018-10-30
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 2018-03-16
      • 1970-01-01
      相关资源
      最近更新 更多