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??
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.
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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With