Snapshot testing react component which depends on inject mobx store - reactjs

I've been trying to figure out how to do simple snapshot testing for a few components that have mobx stores injected into them. Here's an example:
At the root i have a <Provider> wrapping the whole shebang at my final ReactDOM.render() in the entry point. (not shown here)
// component.js
...{imports}...
#inject('mystore')
#observer
export default class extends React.Component {
render() {
return (
<div>Stuff</div>
)
}
}
// component.test.js
import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import Component from './'
it('renders a snapshot', () => {
const tree = renderer.create(<Component/>).toJSON();
expect(tree).toMatchSnapshot();
});
I get a failed test because it's missing a store provided up the tree. I've tried exporting an "undecorated" component like so:
// in component.js
...{same as above}...
export const undecorated = Component
and then importing the undecorated component in my snapshot test, however this doesn't work.
Ideas?

You should be able to pass the store explicitly like so:
const tree = renderer.create(
<Component.wrappedComponent myStore={store}/>).toJSON();
)

Related

ReactWrapper::state() can only be called on class components Unit Testing Jest and Enzyme

Writing unit testing in react using jest and enzyme. While checking with a component state , it throws an error "ReactWrapper::state() can only be called on class components ".
import React from 'react';
import { mount } from 'enzyme';
import expect from 'expect';
import CustomerAdd from '../CustomerAdd'
import MUITheme from '../../../../Utilities/MUITheme';
import { ThemeProvider } from '#material-ui/styles';
describe('<CustomerAdd />', () => {
const wrapper = mount(
<ThemeProvider theme={MUITheme}>
<CustomerAdd {...mockProps}></CustomerAdd>
</ThemeProvider>
);
test('something', () => {
expect(wrapper.find(CustomerAdd).state('addNewOnSubmit')).toEqual(true);
});
});
In the above code CustomerAdd Component is class component.I don't what wrong with my code. Can any one help me out of this problem. Thanks in advance.
So your default export
export default withStyles(styles)(CustomerAdd);
exports functional(HOC) wrapper about your class-based component. And it does not matter if name of class and import in
import CustomerAdd from '../CustomerAdd'
are equal. Your test imports wrapped version and after calling .find(CustomerAdd) returns that HOC not your class. And you're unable to work with instance.
Short time solution: export class directly as named export.
export class CustomerAdd extends React.Component{
...
}
export default withStyles(styles)(CustomerAdd);
Use named import in your tests:
import { CustomerAdd } from '../CusomerAdd';
Quick'n'dirty solution: use .dive to access your underlying class-based component:
expect(wrapper.find(CustomerAdd).dive().state('addNewOnSubmit')).toEqual(true);
It's rather antipattern since if you add any additional HOC in your default export you will need to monkey-patch all related tests with adding appropriate amount of .dive().dive()....dive() calls.
Long-term solution: avoid testing state, it's implementation details.
Instead focus on validating what's been rendered. Then you are safe in case of lot of different refactoring technics like replacing class with functional component, renaming state/instance members, lifting state up, connecting component to Redux etc.

How to access App components with Jest when using Redux container?

I am having some trouble testing components inside App because I am only exporting AppContainer.
const ConnectedApp = connect(mapStateToProps, mapDispatchToProps)(App);
const AppContainer = () => (
<Provider store={clearanceStore}>
<ConnectedApp />
</Provider>
);
export default AppContainer;
How do I test components inside App's return()? This is what I have for a test now which gives an error: Method “simulate” is meant to be run on 1 node. 0 found instead.
test('setSubmit triggered when clicking submit button', () => {
const setSubmit = jest.fn();
const wrapper = shallow(<App />);
const button = wrapper.find('#something');
button.simulate('click');
expect(setSubmit).toHaveBeenCalled();
});
Here is the Redux documentation that should help you:
In a unit test, you would normally import the App component like this:
import App from './App'
However, when you import it, you're actually holding the wrapper component returned by connect(), and not the App component itself. If you want to test its interaction with Redux, this is good news: you can wrap it in a with a store created specifically for this unit test. But sometimes you want to test just the rendering of the component, without a Redux store.
In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component:
import { connect } from 'react-redux'
// Use named export for unconnected component (for tests)
export class App extends Component {
/* ... */
}
// Use default export for the connected component (for app)
export default connect(mapStateToProps)(App)
Since the default export is still the decorated component, the import statement pictured above will work as before so you won't have to change your application code. However, you can now import the undecorated App components in your test file like this:
// Note the curly braces: grab the named export instead of default export
import { App } from './App'
And if you need both:
import ConnectedApp, { App } from './App'
More at https://redux.js.org/recipes/writing-tests

Testing in React Redux

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.
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.

Error while doing unit test in react-redux connected component

I am trying to test the connected component(react-redux) with jest-enzyme. I am using react-redux-mock store. When I run my test to find one div in the component it gives me this error.
Invariant Violation: Passing redux store in props has been removed and does not do anything. To use a custom Redux store for specific components, create a custom React context with React.createContext(), and pass the context object to React-Redux's Provider and specific components like: <Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>. You may also pass a {context : MyContext} option to connect
I did mount and tested just component without redux it works but I want to do a > shallow test.
describe("Input Component", () => {
let wrapper;
let store;
beforeEach(() => {
store = mockStore(initialState);
wrapper = shallow(<Input store={store} />);
});
it("should rendder without error", () => {
expect(wrapper.find("div")).toHaveLength(1);
});
});
How do you import your component?
if your are importing it with import App from './yourpath/App' for example, ou're actually holding the wrapper component returned by connect(), and not the App component itself.
In order to be able to test the App component itself without having to deal with the decorator, you must to also export the undecorated component:
import { connect } from 'react-redux'
// Use named export for unconnected component (for tests)
export class App extends Component {
/* ... */
}
// Use default export for the connected component (for app)
export default connect(mapStateToProps)(App)
And import it in your test file like that:
import { App } from './yourpath/App'

retrieving React child component from Higher Order Component when testing Stateless Functional Component

I am writing jest unit tests for a React Stateless Functional Component (SFC) that is inside a Higher Order Component (HOC). How do I use TestUtils to find a specific class in the SFC?
Specifically, my SFC/HOC looks like:
import React from 'react'
import sizeMe from 'react-sizeme';
const MyClass = ({myText, size}) => {
return (
<div className="MyClassName">{myText}</div>
);
};
export default sizeMe()(MyClass);
Here note that MyClass is a SFC and I am embedding it inside of the HOC sizeMe from the package react-sizeme.
The test I am trying to do is:
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import MyClass from './src/views/MyClass.js'
import Wrap from '../src/views/Wrap'
describe('<MyClass />, () => {
it('can haz my text', () => {
const myClass = TestUtils.renderIntoDocument(
<Wrap>
<MyClass myText={'my text'} />
</Wrap>
);
const myText = TestUtils.findRenderedDOMComponentWithClass(myClass,'MyClassName').innerHTML;
expect(myText).toEqual('myText');
});
});
In this test I am using the utitlity class Wrap that I would normally use to test SFCs:
import React from 'react';
class Wrap extends React.Component {
render() {
return <div>{this.props.children}</div>
}
}
My test fails because TestUtils.findRenderedDOMComponentWithClass cannot find MyClass. I get the message "Did not find exactly one match (found: 0) for class:MyClass"
How can I retrieve MyClass? I would most prefer to use React's TestUtils, but I am open to other approaches if that is not possible.
To get this to work, it is necessary export/import the non-HOCed component. This required 3 changes. First the export keyword should be added to the definition of MyComponent.
export const MyClass = ...
The second change is how MyClass is imported. Since the HOCed MyClass is the default export, exporting the non-HOCed version requires all exports from MyClass.js to be imported as
import * as MC from './src/views/MyClass.js
Finally, the non-HOCed component can now be in the test as
<MC.MyClass myText={'my text'} />
Because the default export was not changed, the HOCed component will still be used in a regular import so no changes to the other parts of the application will be required.

Resources