【问题标题】:_this.store.getState is not a function when testing react component with enzyme and mocha_this.store.getState 在使用酶和摩卡测试反应组件时不是函数
【发布时间】:2017-06-13 10:32:41
【问题描述】:

我正在尝试使用酶和摩卡咖啡测试 React 组件,如下所示

import { mount, shallow } from 'enzyme';
import React from 'react';
import chai, { expect } from 'chai'
import chaiEnzyme from 'chai-enzyme'
import sinon from 'sinon'

import MyComponent from 'myComponent'

chai.use(chaiEnzyme())
describe('MyComponent', () => {
  const store = {
    id: 1
  }
  it ('renders', () => {
    const wrapper = mount(<MyComponent />, {context: {store: store}})
  })
})

实际上并没有编写测试,因为它在声明包装器时失败

错误信息:TypeError: _this.store.getState 不是函数

不知道问题出在哪里,也找不到任何解决此问题的方法!

任何帮助都会很棒!

【问题讨论】:

  • 其实需要通过redux-store。您不能只创建一个常量并将其作为 store 传递。

标签: reactjs testing redux mocha.js enzyme


【解决方案1】:

此错误表示 store 无法正确获取状态。 我建议使用 redux-mock-store 模拟商店 并导入configureStore

import configureStore from 'redux-mock-store';

然后通过这样做来模拟状态

    const initialState = { id: 1 };
    const mockStore = configureStore();

你可以继续用提供者包装你的组件

import { Provider } from 'react-redux'; // add this to the top of your file

const wrapper = mount(
  <Provider store={mockStore(initialState)}>
    <MyComponent />
  </Provider>,
);

【讨论】:

    【解决方案2】:

    另外,在您的代码示例中,chai.user() 不应该是 chai.use() 吗?

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 2020-08-11
      • 2018-01-17
      • 2015-05-23
      相关资源
      最近更新 更多