Jest test component's inner method - reactjs

I'm using react native 0.40 with jest 20. When trying to test the inner method of a component I fail because I cannot get the instance of it and then call the method.
For example I can test the rendered component using the snapshots like
it('renders correctly', () => {
var store = mockStore(initialState);
const tree = renderer.create(
<Provider store={store}>
<App/>
</Provider>
).toJSON()
expect(tree).toMatchSnapshot()
})
But if I try to test an inner method of the App component I don't find any way to access it.
So the following code will not run
it("checks version number correctly", () => {
var store = mockStore(initialState);
const tree = renderer.create(
<Provider store={store}>
<App/>
</Provider>
)
expect(tree.needsUpdate("1.0.0")).toBe(true)
})
The solution some people used was "react-test-renderer/shallow" or "enzyme" to shallow render the component and access the inner method, but the first one cannot be found when I import it (maybe related to RN version?) and enzyme cannot be installed properly (maybe again, a dependency issue). So what I wonder is, what's the best way to test an inner method.

You don't have to actually wrap your component in a provider. If you just want to test your component, you can export it without connect()(). For instance:
export class App extends React.Component {
// your things
}
export default connect()(App);
Inside your test file, you can import your app like so:
import ConnectedApp, { App } from "../App";
Then when you want to test your encapsulated App, you can treat it like any other standard component:
const props = {
// mocked-out props your store would provide
};
const component = shallow(<App {...props} />);
component.instance().whateverMethodYouWant();
Personally, I never wrap a component in a mock provider unless I need to render and deeper components are connected.

Related

Jest mocking return value of a static method of connected component

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}/>)

React Jest Enzyme : Unable to pass router parameter

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.

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'

Mocking Redux store when testing React components?

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)

JEST testing on redux is not working as expected

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>

Resources