Redux选择器的单元测试

时间:2018-10-24 15:15:32

标签: reactjs unit-testing react-redux chai immutable.js

请建议我如何在react中为下面的selector.js文件编写单元测试

import {createStructuredSelector, createSelector} from 'reselect'
import {List, OrderedMap, fromJS, Map} from 'immutable'

const kpi_graphs = (state) => state.getIn(['myReducer', 'kpi_graphs'], List())
const show_chart = (state) => state.getIn(['myReducer', "isShowChart"])

export const kpiData = createStructuredSelector({ 
 raw_kpi_graph: kpi_graphs,
 isShowChart:show_chart
})

1 个答案:

答案 0 :(得分:0)

createStructuredSelector({inputSelectors}, selectorCreator = createSelector) 返回一个结构化选择器函数,该函数接受 redux 状态树作为其参数。因此,您可以像测试 JavaScript 函数一样对其进行测试。

软件包版本:

"reselect": "^4.0.0",
"immutable": "^4.0.0-rc.12",

例如

selector.js

import { createStructuredSelector } from 'reselect';
import { List } from 'immutable';

const kpi_graphs = (state) => state.getIn(['myReducer', 'kpi_graphs'], List());
const show_chart = (state) => state.getIn(['myReducer', 'isShowChart']);

export const kpiData = createStructuredSelector({
  raw_kpi_graph: kpi_graphs,
  isShowChart: show_chart,
});

selector.test.js

import { kpiData } from './selector';
import { Map, List } from 'immutable';
import { expect } from 'chai';

describe('52972539', () => {
  it('should create structed selector correctly if there is a kpi_graphs slice in reducer', () => {
    const state = Map({
      myReducer: {
        kpi_graphs: 'a',
        isShowChart: true,
      },
    });
    const actual = kpiData(state);
    expect(actual).to.deep.equal({ raw_kpi_graph: 'a', isShowChart: true });
  });

  it('should create structed selector correctly if there is no kpi_graphs slice in reducer', () => {
    const state = Map({
      myReducer: {
        isShowChart: true,
      },
    });
    const actual = kpiData(state);
    expect(actual).to.deep.equal({ raw_kpi_graph: List(), isShowChart: true });
  });
});

单元测试结果:

  52972539
    ✓ should create structed selector correctly if there is a kpi_graphs slice in reducer
    ✓ should create structed selector correctly if there is no kpi_graphs slice in reducer


  2 passing (7ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |      100 |     100 |     100 |                   
 selector.ts |     100 |      100 |     100 |     100 |                   
-------------|---------|----------|---------|---------|-------------------