redux - 开 Jest 测试: "state.get is not a function"

标签 redux jestjs immutable.js

我正在尝试使用 jest 测试计数器 reducer ,但在分派(dispatch) INCRMENT 时收到 TypeError: state.get is not a function。 这是我的代码...

// module.js
import { fromJS } from 'immutable';
...

const initialState = fromJS({
  value: 0,
});

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case INCREMENT:
      return state.set('value', state.get('value') + 1);
    case DECREMENT:
      return state.set('value', state.get('value') - 1);
    case INCREMENT_IF_ODD:
      return (state % 2 !== 0) ? state.set('value', state.get('value') + 1) : state;
    default:
      return state;
  }
}

// module.test.js
import { fromJS } from 'immutable';

import reducer, { types } from './module';

const { INCREMENT, DECREMENT, INCREMENT_IF_ODD } = types;

describe('Counter reducer', () => {
  it('should return the initial state', () => {
    expect(reducer(undefined, {})).toEqual(fromJS({
      value: 0,
    }));
  });

  it(`should handle ${INCREMENT}`, () => {
    expect(reducer(0, { type: INCREMENT })).toEqual(fromJS({
      value: 1,
    }));
  });

  ...
});

我不明白我的代码有什么问题,因为它在浏览器上运行正常。

这里是错误

 FAIL  src/containers/Counter/module.test.js
  ● Counter reducer › should handle Counter/INCREMENT

    TypeError: state.get is not a function

      at reducer (src/containers/Counter/module.js:34:50)
      at Object.<anonymous> (src/containers/Counter/module.test.js:25:33)
          at new Promise (<anonymous>)
          at <anonymous>

最佳答案

错误是因为传递给reducer的store是0,所以在reducer函数内部尝试执行0.get(..)。 传递给 reducer 的第一个参数应该是初始存储:

it(`should handle ${INCREMENT}`, () => {
  const initialState = fromJS({
    value: 0,
  });

  expect(reducer(initialState, { type: INCREMENT })).toEqual(fromJS({
    value: 1,
  }));
});

关于redux - 开 Jest 测试: "state.get is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687791/

相关文章:

javascript - 不可变 JS 比较嵌套结构

javascript - 使用 D3.js 和 Immutable.js

javascript - 用于填充 React 组件中下拉列表的多个 API 调用

node.js - fastify,在fastify实例上开 Jest : running processes after calling . close()

javascript - 使用 Jest 进行测试时,是否有更快的方法来重置模拟?

react-native - 如何使用 enzyme Jest 为 React Native 中的导航堆栈编写单元测试用例?

javascript - 为什么不可变不会提示尝试改变值(value)

javascript - Redux Store 不会使用 firebase 实时数据库上创建的数据更新状态

reactjs - 如何获取调度函数引用和操作创建器作为任何连接组件内的 Prop

reactjs - Graphql & Relay 制作案例