Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a Redux-connected component using Enzyme

Tags:

reactjs

enzyme

have problem with testing redux connected component with enzyme

import React from 'react'
import { shallow, mount, render } from 'enzyme'
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import Login from '../../src/routes/login/components/Login'

configure({ adapter: new Adapter() })

describe('<Login />', () => {
    test('component has form-group nodes', () => {
        const component = shallow(<Login />).dive()
        expect(component.find('.form-group')).to.have.length(2)
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

But have error in console - Invariant Violation: Could not find "store" in either the context or props of "Connect(Login)".

how to deal with it??

like image 693
Dmytro P Avatar asked Mar 23 '18 09:03

Dmytro P


People also ask

Can we use Enzyme and React testing library together?

A few days ago, React released version 18, which is not compatible with Enzyme. Furthermore, it probably is not achievable to use Enzyme with React 18. If you're still using Enzyme, it is time to look into alternatives. The most popular option besides Enzyme seems to be React Testing Library.

How does a Redux connected component know when to re render?

It deduces the changes of your data by running the reducer function you provide, and returns the next state that corresponds to every action dispatched. React Redux then optimizes component rendering and makes sure that each component re-renders only when the data it needs change.

What is the purpose of the connect () function in Redux?

Overview​ The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.


1 Answers

I faced a similar problem and I managed to solve it by using redux-mock-store for my store mocking and I used mount instead of shallow to reach my connected component with redux like that:

import React, { Component } from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import App from '../../src/App';

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

  const mockStore = configureStore();
  const initialState = {
    someState: [],
    someReducer: {},
  };

  const store = mockStore(initialState);

  const wrapper = mount(
    <Provider store={store}>
      <App />
    </Provider>
  );

  console.log(wrapper.debug())

  expect(wrapper.find('.app-container')).to.have.lengthOf(1);
});
like image 167
Muho Avatar answered Sep 29 '22 02:09

Muho