TL;DR
Introducing react-performance-testing that is new React test library to measure performance(number of renders, render time).
Why?
If you are developing high-performance features, you would like to write test about the number of renders or render time. However we have to check with devtools or Lighthouse manually, and we could not test these cases automatically. Additionally, we cannot predict re-renders without getting nervous. The react-performance-testing provides a solution for these cases.
Solution
The react-performance-testing provides a simple and easy way as a solution for the above problem. It provides some features by monkey patched React. We can count the number of renders and measure renders time as well, and we can test by using these values.
How to use?
You can use perf
and wait
method.
perf
method is used to measure rendering performance. This lib measure rendering performance by wrapping your component with own component internally. But this component is very small, so this component do not affect to your component.
wait
method is used wait for rendering process is completed. This is because, this lib measure performance after rendering process is completed.
You can use as bellow.
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import { perf, wait } from 'react-performance-testing';
test('should render two times when count button is clicked', async () => {
const Button = ({ name, onClick }) => (
<button type="button" onClick={onClick}>{name}</button>
);
const Counter = () => {
const [count, setCount] = React.useState(0);
return (
<div>
<span>{count}</span>
<Button name="count" onClick={() => setCount(c => c + 1)}/>
</div>
);
};
// This lib monkey patches React in perf method.
// So, you need to pass React module.
const { renderCount } = perf(React);
fireEvent.click(screen.getByRole('button', { name: /count/i }));
// renderCount.current have each component name object,
// and it have number of renders in its `value` property.
await wait(() => {
expect(renderCount.current.Counter.value).toBe(2);
expect(renderCount.current.Button.value).toBe(2);
});
});
Note that you should use wait
method. This is because, renderCount
is assigned value after React's render process is completed.
Thanks
Thank you very much for reading.
If you want to test about number of renders, please try it!
I hope this lib will be helpful for you.
Here is repository: https://github.com/keiya01/react-performance-testing
Top comments (0)