I am unit testing my React app with jest and enzyme and all is good until I happened to test a class component connected with Redux. I went ahead and tested it by wrapping the component with a and then shallow mounting it. However I am not able to run assertions after updating the props of component, nor I am able to spy on the class methods being called or not.
Below is my sample code:
const wrapper = shallow(
<Provider store={store}>
<TestComponent {...props} />
</Provider>
).dive();
Now when I try t set the props of the wrapper and run assertions, it fails:
wrapper.setProps({
showHeader: true
})
expect(wrapper.find('h1')).toHaveLength(1);
Interesting part is, if I export the unconnected component as also suggested in redux docs, the assertions work well. Is it fine to export the unconnected component just for the purpose of testing? I can't spy on instance methods/lifecycle methods if I try to test the connected component.
You can mock the connect function from react-redux to return the original component
jest.mock('react-redux', () => ({
connect: () => Component => Component
}))
Related
I am unit testing my React app with jest and enzyme and all is good until I happened to test a class component connected with Redux. I went ahead and tested it by wrapping the component with a and then shallow mounting it. However I am not able to mock return value of the static methods defined in my connected component.
Below is my sample code:
const wrapper = shallow(
<Provider store={store}>
<TestComponent {...props} />
</Provider>
).dive();
Now when I try to mock the return value of static method defined in TestComponent, it doesn't have any effect, it fails:
TestComponent.myStaticMethod = jest.fn().mockReturnValue(true);
Interesting part is, if I export the unconnected component as also suggested in redux docs, the above mock syntax work well. Is it fine to export the unconnected component just for the purpose of testing? I tried mocking before the shallow and then after it, both ways didn't work.
connect returns a new component so you cannot override the static methods of the wrapped component in this way, (which is not a good idea like Andrew said)
But assuming this is what you want to do, you can mock the connect function from react-redux to return the original component
then pass all the props it gets from mapStateToProps and mapDispatchToProps as a standard React props
import MyComponent from './MyComponent';
jest.mock('react-redux' () => ({
connect: () => Component => Component
}))
MyComponent.myStaticMethod = jest.fn().mockReturnValue(true);
shallow(<MyComponent {...props}/>)
I have a component named AddEditVehicle which renders when the route is /vehicle/:vehicleId/edit.
I need to test the React lifecycles of this component. So I have used Enzyme mount to render my component in the unit test in the following way.
beforeEach(async () => {
wrapper = await mount(
<BrowserRouter>
<Provider store={store}>
<AddEditVehicle match={{ params: { vehicleId } }} />
</Provider>
</BrowserRouter>
);
await wrapper.update();
});
this wrapper fails to pass the required params making following specs to fail.
it("expect `isEditMode` value to set", () => {
const componentState = wrapper.find("AddEditVehicle").instance().state;
expect(componentState.isEditMode).toEqual(true);
});
Versions :
react ^16.4.2
react-router ^4.3.1
jest ^23.5.0
enzyme ^3.4.4
The problem with my approach was my Component was part of a Route but still, I was wrapping the component with withRouter which is redundant. So, in the unit test when I was passing the Route match details it was getting overridded. Thus, removing the withRouter made the solution work.
I'm using React and Redux. I have a component which loads ChildComponent and depending on Redux's state will also load MainComponent
const ChooseIndex = ({ appInitMount }) => {
return (
<>
<ChildComponent />
{!appInitMount && <MainComponent />}
</>
);
};
const mapStateToProps = ({ main }) => {
return {
appInitMount: main.appInitMount
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ChooseIndex);
I'm trying to write a test to check that ChildComponent is loaded:
import React from "react";
import { render } from "react-testing-library";
import ChooseIndex from "../choose-index";
test("ChooseIndex should call ChildComponent", () => {
const wrapper = render(
<ChooseIndex />
);
});
I get this error:
Error: Uncaught [Invariant Violation: Could not find "store" in either
the context or props of "Connect(ChooseIndex)". Either wrap the root
component in a , or explicitly pass "store" as a prop to
"Connect(ChooseIndex)".]
Should I mock Redux by passing an object literal to ChooseIndex? Or should I create a Redux store (as my real application does) for every test?
Try to render your component like this:
render(
<Provider store={store}>
<ChooseIndex />
</Provider>
)
And pass the actual store you use in your app. In this way, you're testing the real logic that you'll use in production. You also don't care what actions get dispatched and what's in the state. You look at what gets rendered and interact with the UI—which is what matters in the end.
Separating the component from Redux and testing the two in isolation is against the whole point of react-testing-library. You want to test your app as a real user would.
If you check out the writing tests section of the redux docs, there is an example of testing a connected component.
when you import it [A redux connected component], 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
As with most unit tests, you really want to be testing your components, and not that redux is working correctly. So the solution for you is to export both the component and the connected component, while only testing the component itself, and providing whatever props redux is passing to your 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)
I have a code in redux which i exported as
export default connect(mapStateToLinkProps, mapDispatchToLinkProps)(Link);
And in jest test case i have written to test this exported component
//imported the above component as Link
describe('Dashboard component testing', () => {
test('1. Must be an Instance of CreateAssest', () => {
const wrapper = shallow(<FilterLink />);
const inst = wrapper.instance();
expect(inst).toBeInstanceOf(Link);
});
});
For this i'm getting error
Invariant Violation: Could not find "store" in either the context or
props of "Connect(Link)". Either wrap the root component in a
, or explicitly pass "store" as a prop to "Connect(Link)".
When not using redux and exporting only as react component the test cases were working.Now in redux some store issue is coming.please can anyone guide a little in this issue what's happening
You need to wrap your component in Provider in order to be able to use store, like so:
import { Provider, connect } from "react-redux";
let store = createStore(reducer, defaultStoreItems);
<Provider store={store}>
<App />
</Provider>
How can I test a Reaect-Redux component and mock its context and actions?
With this, it can't find any actions:
const wrapper = mount(
<S437TransactionAuth
store={store}
s437updateGui="{mock.action.s437updateGUI}"
setCurrentUserId="{mock.action.setCurrentUserId}"
/>,
mockContext
);
This can't find mock actions or context
const wrapper = mount(
<Provider store={store}>
<S437TransactionAuth
s437updateGui="{mock.action.s437updateGUI}"
setCurrentUserId="{mock.action.setCurrentUserId}"
/>
</Provider>,
mockContext
);
What is the standard practice? I'm using Mocha, for reasons beyond my control.
Our standard practice is to export both the connect component as default and the component itself as a named export.
connect is already tested for you so there's no point in verifying it's actually passing stuff from the Redux store to your component. What you can test is that your component uses that props correctly, which you can mock in your non-connected component.
You can also test your selectors and action creators you assign in mapStateToProps and mapDispatchToProps in isolation.
Last but not least, you can always simply configure your real store for the test (inside your describecalls!) and wrap your subject in a Provider with the real store. But this path could lead to you having to dispatch some actions to setup the state as your component expects it (like mocking an API call to have data, and so on).
Assuming you are using enzyme for doing the mounting, the context is supposed to be passed as
const wrapper = mount(
<S437TransactionAuth
// I'm assuming you have put your store in the context so I've removed store={store} for here
s437updateGui="{mock.action.s437updateGUI}"
setCurrentUserId="{mock.action.setCurrentUserId}"
/>,
{ context: mockContext }
);
I've personally just used the react-redux Provider without doing anything with the second parameter of mount, like so
const wrapper = mount(
<Provider store={store}>
<S437TransactionAuth
s437updateGui="{mock.action.s437updateGUI}"
setCurrentUserId="{mock.action.setCurrentUserId}"
/>
</Provider>
);
Also, if you're not already using it, redux-mock-store makes testing connected components much easier but allowing you to set up an initial state to render, assert expected render in the component, or simulate user actions on the component with enzyme, and assert the expected actions against the mock store.