Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_this.store.getState is not a function when testing react component with enzyme and mocha

I'm trying to test a React component with enzyme and mocha as follows

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}})
  })
})

haven't actually written the test as it fails at the declaration of wrapper

Error message: TypeError: _this.store.getState is not a function

No idea what the problem is and cant find anything addressing this!

Any help would be great!

like image 893
michaeljacques Avatar asked Jan 27 '17 16:01

michaeljacques


1 Answers

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';

then mock the state by doing this

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

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>,
);
like image 108
Nagy Wesley Avatar answered Dec 04 '22 04:12

Nagy Wesley