score:13
Do I have to wrap in every single test suite with <Suspense>
?
Yes, the
Suspense
component is neccessary for lazily loading child components, particularly providing a fallback and for reconciliation when the lazy components are available.
Export Component1
and Component2
in CustomComponent
so that they can be imported in tests.
import React, {PureComponent, lazy} from 'react';
export const Component1 = lazy(() => import('./Component1'));
export const Component2 = lazy(() => import('./Component2'));
export default class CustomComponent extends PureComponent {
//...
}
Remember that the lazy loaded components are promise-like. Import them in the test, and wait for them to resolve before doing a check that the snapshot matches.
import { create } from 'react-test-renderer';
import React, {Suspense} from 'react';
import CustomComponent, {Component1, Component2} from './LazyComponent';
describe('CustomComponent', () => {
it('rendered lazily', async()=> {
const root = create(
<Suspense fallback={<div>loading...</div>}>
<CustomComponent/>
</Suspense>
);
await Component1;
await Component2;
expect(root).toMatchSnapshot();
})
})
score:0
In a way a combination of the two answers is the only thing that worked for me (using enzyme mount)
I had to use the export logic of the accepted answer and the await logic of Raine's answer
//use at own risk
await (Component1 as any)._ctor();
wrapper.update()
Raine's answer did not work on our build agent somehow, but worked on the dev environment
score:2
I had a similar problem where I wanted to do snapshot testing of nested components and one of them where lazy loaded. The nesting looked something like this:
SalesContainer -> SalesAreaCard -> SalesCard -> AreaMap
Where SalesContainer
is the top component. The AreaMap
-component is lazy loaded by SalesCard
using React lazy and Suspense. The tests passed locally with AreaMap
rendered in the snapshot for most developers. But the tests always failed miserably in Jenkins CI with the AreaMap
never rendered. Flaky to say the least.
To make the tests pass I added the magic line await testRenderer.getInstance().loadingPromise;
to the tests. This is an example of a test:
import React from 'react';
import renderer from 'react-test-renderer';
import wait from 'waait';
import SalesContainer from './index';
describe('<SalesContainer />', () => {
it('should render correctly', async () => {
const testRenderer = renderer.create(
<SalesContainer />
);
await wait(0);
await testRenderer.getInstance().loadingPromise;
expect(testRenderer).toMatchSnapshot();
});
});
score:3
With Enzyme and mount this worked for me. It does not require changing any exports.
// wait for lazy components
await import('./Component1')
await import('./Component2')
jest.runOnlyPendingTimers()
wrapper.update()
Thanks to Andrew Ferk's comment on the accepted answer.
score:4
As per this comment in github, you can mock the lazy components with Jest to return the actual components instead, although you would need to move and export lazy statements to their own files for it to work.
// LazyComponent1.ts
import { lazy } from 'react';
export default lazy(() => import('./Component1'));
// CustomComponent.tsx
import React, { PureComponent } from 'react';
import Component1 from './LazyComponent1';
import Component2 from './LazyComponent2';
class CustomComponent extends PureComponent {
...
render() {
return (
<div>
<Component1 />
<Component2 />
</div>
);
}
}
// CustomComponent.spec.tsx
import React, { Suspense } from 'react';
import { create } from 'react-test-renderer';
import CustomComponent from './CustomComponent';
jest.mock('./LazyComponent1', () => require('./Component1'));
jest.mock('./LazyComponent2', () => require('./Component2'));
describe('CustomComponent', () => {
it('should show the component', () => {
const component = await create(
<Suspense fallback={<div>loading</div>}>
<CustomComponent />
</Suspense>
);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
Source: stackoverflow.com
Related Query
- How to test snapshots with Jest and new React lazy 16.6 API
- How to test a className with the Jest and React testing library
- How to test form submission in React with Jest and Enzyme? Cannot read property 'preventDefault' of undefined
- How to test API calls in react using jest and enzyme?
- how can I test if useState hook has been called with jest and react testing library?
- How to test redux state update with react testing library and jest
- How to test with jest and typescript with types a basic react function component
- How to test a React component that has Router, Redux and two HOCs... with Jest and Enzyme?
- How to check the value of a nested React component in a unit test with Enzyme and Jest
- How to test functions in React with Jest and Enzyme
- How to test styles and media queries rendered by a React component with Jest and/or Enzyme
- How to test axios api using jest and react testing library?
- How to test a React component that update over time with Jest and Enzyme?
- How to Test a function with Jest and React
- Jest with React - How do you render an entire component and test it?
- How to test async handleSubmit(e) in react with jest and enzyme
- How do I unit test amcharts using jest with react and typescript?
- How to test React component with children using jest and enzyme?
- How to test asynchronous function with rtl and jest in React
- How to write a test with Jest and React testing library to check if anchor-tag <a /> exist
- How to test React with hooks and PubSub-js with Jest Enzyme
- how to test component while passing boolean value with react testing library and jest
- How do I test my actions, state and UI. I'm using context API with jest and testing-library?
- How to mock React component methods with jest and enzyme
- How to mock history.push with the new React Router Hooks using Jest
- How to make react router work with static assets, html5 mode, history API and nested routes?
- How to unit test a react event handler that contains history.push using Jest and Enzyme?
- How should the new context api work with React Native navigator?
- How do you test router match params with jest and enzyme?
- How to test a component with a nested container with React and Redux?
More Query from same tag
- How to map deep JSON data dynamically using React
- Using react2angular, react isn't recognized, no erros
- Change Semantic UI's Pagination icon
- React cropper cannot use it two times in a row
- Cannot append to formData object on file upload in React
- React ref using reactstrap Input Module doesn't have Value prop
- Page loads before user data is saved from useEffect() to useContext() in React.js
- Uncaught Error: Expected `onClick` listener to be a function, instead got a value of `object` type. ReactJS
- setstate inside render method - Reactjs
- How to set watcher to get know if a particular mutation was called
- I cannot change font-color in TextField component from Material UI
- How to use formik with Antd Design Form?
- I try to override materialUI inbuilt classes using CSS file, styles are applying all the components in React how to stop overriding styles globally?
- Dropdown Value not passing from one component to the other - React JS
- react js component polymorphism
- How to find out which Router component is being rendered in React?
- Accessing URL param in react-router render function
- Not Able to get request body as desired
- Mantine form, prevent closing mantine modal after submitting
- How could I store multiple values to one reusable variable - reactJs
- React.createElement: type is invalid -- expected a string
- 'react-router-dom' does not contain an export named 'useHistory'
- React const in alert box
- Refactoring javascript code react redux issue
- Bootstrap Nav bar doesn't work properly on mobile
- How to run Front End and Backend together in React.js and Express.js
- ReactJS: Single onChange handler for multiple form inputs
- Set initial const based on viewport width react js
- Possible to swap react components out via onClick's?
- Cant pass array of objects to setPeople function in React