user1261710
user1261710

Reputation: 2639

How can I fix this broken unit test after adding Redux to my ReactJS app?

My app runs fine and here is the main file:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from '../src/store/store';

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);

I originally used react create an app to make my project as found here: https://github.com/facebookincubator/create-react-app and then I added Redux to my app.

After I added Redux to my app for state management, the original unit test broke.

Here is the test:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});

How can I fix the unit test so that it passes?

Upvotes: 1

Views: 508

Answers (2)

I Am
I Am

Reputation: 33

When you add Redux to your app, you will need to initialize your app in test with mock store. Much the same what Michael said.

Upvotes: 0

Michael Peyper
Michael Peyper

Reputation: 6944

You haven't given much detail about the error you are getting, but I'll presume it's to do with not having a store for a connected component.

You can use something like redux-mock-store to create an expected state and then wrap App in a Provider just like you did in the main file. Something like

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store'
import App from './App';

const middlewares = []
const mockStore = configureStore(middlewares)

it('renders without crashing', () => {

  const initialState = { /*expected state goes here */ }
  const store = mockStore(initialState)

  const div = document.createElement('div');
  ReactDOM.render(<Provider store={store}><App /></Provider>, div);
});

NOTE: I also just want to warn you that this test might be useful to you now, but the more complex your app gets, the harder it will be to maintain as more and more state is required to render. You may want to look into tools like enzyme and using shallow renders of individual components to test you app instead.

Upvotes: 1

Related Questions