I have a component animated with react-spring
using the useSpring
hook. Something like:
function Toggle({ handleToggle, toggled }) {
const x = useSpring({
x: toggled ? 1 : 0
});
return (
<div className={styles.switch} onToggle={handleToggle} data-testid="switch">
<animated.div
className={styles.circle}
style={{
transform: x
.interpolate({
range: [0, 0.4, 0.8, 1],
output: [0, 5, 10, 16]
})
.interpolate((x) => `translateX(${x}px)`)
}}>
</animated.div>
</div>
);
}
When testing the component a warning is thrown:
Warning: An update to ForwardRef inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/docs/test-utils.html#act
in ForwardRef (created by Toggle)
in Toggle
The code for my test is:
test("Toggle works", () => {
let toggled = false;
const handleToggle = jest.fn(() => {
toggled = true;
});
const { getByTestId, queryByTestId } = render(
<Toggle toggled={toggled} handleToggle={handleToggle}/>
);
});
How should I test components animated with react-spring
using @testing-library/react
?
I had this warning while testing a component that uses useSpring
and <animated.div>
in a react-test-renderer
renderer snapshot creation:
import renderer from 'react-test-renderer';
//(...)
it('matches snapshot', () => {
const tree = renderer.create(<Component />).toJSON();
expect(tree).toMatchSnapshot();
});
//(...)
I've found inspiration in this link, and could solve it just by adding the Jest's useFakeTimers
call:
import renderer from 'react-test-renderer';
//(...)
it('matches snapshot', () => {
jest.useFakeTimers(); //ADDED
const tree = renderer.create(<Component />).toJSON();
expect(tree).toMatchSnapshot();
});
//(...)
See that wrapping stuff with act
, like in the referenced link, was not necessary in this case.
While researching I also found this following blog post, that explains the reasons and describes some cases in which this warning is shown, including a case when you do use jest.useFakeTimers()
, the warning keeps being displayed and using act
is necessary: Fix the "not wrapped in act(...)" warning