如何用jest测试减速器

问题描述 投票:0回答:1

我有这个减速器。

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)

我怎样才能把测试加入到这些减速器中去呢? 因为这是redux sagas,我是按照这个来做的。https:/redux.js.orgrecipeswriting-tests。 由于它是我找到的文档,这是更接近我的需求。

redux-saga jest
1个回答
1
投票

你的reducer期望得到 state 它被视为 immutable 对象,但在你的第二个测试中,你传给它一个普通的javascript对象。

但在你的第二个测试中,你给它传递了一个普通的javascript对象,而这个对象没有 .set 方法,或者在这种特殊情况下,你可以把它传给你试图调用的方法。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.