如何用 jest 测试 reducer

how to test reducers with jest

我有这个减速器:

import { fromJS } from 'immutable';
import { DEFAULT_ACTION, SOURCES_LOADED, SOURCES_REQUEST } from './constants';

export const initialState = fromJS({
  sources: null,
  loading: false
});

function appReducer(state = initialState, action) {
  switch (action.type) {
    case SOURCES_REQUEST:
      return state
        .set('loading', true);
    case SOURCES_LOADED:
      return state
        .set('sources', action.payload.sources)
        .set('loading', false);
    case DEFAULT_ACTION:
      return state;
    default:
      return state;
  }
}

export default appReducer;

这个测试:

import { fromJS } from 'immutable';
import reducer from '../reducer';
import * as types from '../constants';

describe('application reducers', () => {
  it('should return the initial state', () => {
    expect(reducer(undefined, {})).toEqual(fromJS(
      {
        sources: null,
        loading: false
      }
    ));
  });

  it('should handle the sources request', () => {
    expect(reducer({ loading: true }, {
      type: types.SOURCES_REQUEST
    })).toEqual(fromJS({ loading: true }));
  });
});

第二个测试失败:

TypeError: state.set is not a function

      11 |     case SOURCES_REQUEST:
      12 |       return state
    > 13 |         .set('loading', true);
         |          ^
      14 |     case SOURCES_LOADED:
      15 |       return state
      16 |         .set('sources', action.payload.sources)

我如何将测试添加到这些 reducer,因为这是 redux 传奇,我正在关注这个 https://redux.js.org/recipes/writing-tests 因为它是我找到的更接近我需要的文档。

你的 reducer 期望它收到的 state 是一个 immutable 对象。

但是在你的第二次测试中,你传递给它一个普通的 javascript 对象,它没有你尝试调用的 .set 方法。

it('should handle the sources request', () => {
  expect(reducer(fromJS({
    loading: true
  }), {
    type: types.SOURCES_REQUEST
  })).toEqual(fromJS({
    loading: true
  }));
});

或者在这种特殊情况下你可以传递它 undefined 并且减速器将使用 initialState