0

I have Dashboard component like below.

import React, { Component } from 'react';
import DataTable from './DataTable';
import { connect } from 'react-redux';

class Dashboard extends Component {
  render() {
    return <DataTable />;
  }
}

export default connect()(Dashboard);

My test is like below

App.test.js

import React from 'react';
import ReactDOM from 'react-dom';
import Dashboard from './components/Dashboard';


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


describe('Addition', () => {
  it('knows that 2 and 2 make 4', () => {
    expect(2 + 2).toBe(4);
  });
});

I am trying to run test using this command npm test App.test.js.

I am getting below error

Invariant Violation: Could not find "store" in the context of "Connect(Dashboard)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(Dashboard) in connect options.

enter image description here

1 Answer 1

1

Your Dashboard is connected to redux, which requires a store. You have a two possibilities :

  • use Enzyme and redux-mock-store in order to configure a store used when you're mounting your component. This is not well maintainable and leads to a strong dependency between Component and store.

  • export the non-connected Dashboard (in addition to the default export connected), and mount (eventually with the required props). This is much simpler and maintainable.

export class Dashboard extends Component {
   render() {
     return <DataTable />;
   }
}


// Test :

import { Dashboard } from './components/Dashboard';

ReactDOM.render(<Dashboard />, div);

Note: I think you simplified your connect() for the example purpose, because it does not do anything here, but if this is your real implementation you could drop the connect part and still use the default export for your test.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @colinux for your reply. I have connect() in <DataTable /> component also. As per your reply ReactDOM is unable handle this situation, I have to use Enzyme instead of ReactDOM, right ?
@abuabu you can also test Datatable the same way , and just ensuring Dashboard renders a Datatable component. There is also react-testing-library which becomes popular theses days, which test from an user perspective testing-library.com
Thanks @colinux. As per your reply ReactDOM is unable handle this situation, I have to use Enzyme instead of ReactDOM, right ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.