Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-testing-library: Could not find "store" in the context of component

I'm quite new to testing so try to be gentle! I am trying to set up react-testing-library and I'm stuck with a confusing error message:

I defined a custom renderer that contains all my providers incl. redux Provider:

import React from 'react';
import { render } from '@testing-library/react'
import { ThemeProvider } from 'styled-components';
import { defaultTheme } from 'shared/theme';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from 'reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

const AllTheProviders = ({ children }) => {
  return (
      <Provider store={store}>
        <ThemeProvider theme={defaultTheme}>
            {children}
        </ThemeProvider>
      </Provider>
  )
}

const customRender = (ui, options?) =>
  render(ui, { wrapper: AllTheProviders, ...options })

// re-export everything
export * from '@testing-library/react'

// override render method
export { customRender as render }

But when trying to execute the test I am receiving the error Message:

Error: Uncaught [Invariant Violation: Could not find "store" in the context of "Connect(withRouter(Header))". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(withRouter(Header)) in connect options.]

As far as I can see, I included the store. Is there a way around this?

This question is not a duplicate of: Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)" Since it involves a global renderer.

like image 405
Xen_mar Avatar asked Nov 07 '22 09:11

Xen_mar


1 Answers

The store needs to be mocked in order to test properly. I suggest to use redux-mock-store library to achieve that but it's up to your preference.

What I would try in your case is the following in the test file:

import configureMockStore from 'redux-mock-store';

const mockStore = configureMockStore();
const store = mockStore({ /* here you can create a mock object for the reducer */ });

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<Provider store={store}>
                     { /* your components */ }
                  </Provider>, div);
  ReactDOM.unmountComponentAtNode(div);
});

I hope this gives you the idea and helps!

like image 129
norbitrial Avatar answered Nov 14 '22 23:11

norbitrial