_this.store.getState 不是用酶和摩卡测试反应组件时的函数

mic*_*ues 8 testing mocha.js reactjs redux enzyme

我试图用酶和摩卡来测试一个 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}})
  })
})
Run Code Online (Sandbox Code Playgroud)

实际上还没有编写测试,因为它在包装器的声明中失败了

错误信息:TypeError: _this.store.getState is not a function

不知道问题是什么,也找不到任何解决此问题的方法!

任何帮助都会很棒!

小智 6

This error means that store can't get the state correctly. I would recommend mocking the store using redux-mock-store and import configureStore

import configureStore from 'redux-mock-store';
Run Code Online (Sandbox Code Playgroud)

then mock the state by doing this

    const initialState = { id: 1 };
    const mockStore = configureStore();
Run Code Online (Sandbox Code Playgroud)

and you can continue by wrapping your component with provider

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

const wrapper = mount(
  <Provider store={mockStore(initialState)}>
    <MyComponent />
  </Provider>,
);
Run Code Online (Sandbox Code Playgroud)


小智 0

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