Testing with Jest
Reanimated provides testing API, based on Jest. It allows user to mock web-based animations.
Reference
test('reference', () => {
// some styles
const { getByTestId } = render(<AnimatedComponent />);
const view = getByTestId('view');
const button = getByTestId('button');
expect(view).toHaveAnimatedStyle(style);
fireEvent.press(button);
jest.advanceTimersByTime(250); // if whole animation duration is a 500ms
style.width = 50; // value of component width after 250ms of animation
expect(view).toHaveAnimatedStyle(style);
});
Setup
Add the following line to your jest-setup.js
file:
require('react-native-reanimated').setUpTests();
setUpTests()
can take optional config argument. Default config is{ fps: 60 }
.
To be sure, check if your jest.config.js
file contains:
...
preset: 'react-native',
setupFilesAfterEnv: ['./jest-setup.js'],
...
If you use Jest in a version older than 28, you should set setupFiles
property instead of setupFilesAfterEnv
API
Style checker
expect(component).toHaveAnimatedStyle(expectedStyle)
Checking equality of selected styles with current component styles.
component
- tested component.expectedStyle
- contains expected styles of testing component, for example{ width: 100 }
.
expect(component).toHaveAnimatedStyle(expectedStyle, {exact: true})
Checking equality of all current component styles with expected styles.
getDefaultStyle(component)
Gets all styles of tested component.
Timers
You can use Jest's fake timers to control animation progress. Check the full guide about mocking timers on Jest documentation website.
jest.useFakeTimers();
// call animation
jest.runAllTimers();
If you want more control over animation, you can use jest.advanceTimersByTime
to move to a certain point in the animation:
jest.useFakeTimers();
// call animation
jest.advanceTimersByTime(250);
// make assertions on what you expect the styles of a component should be after 250ms
Example
test('withTiming animation', () => {
const style = getDefaultStyle();
const { getByTestId } = render(<AnimatedComponent />);
const view = getByTestId('view');
const button = getByTestId('button');
expect(view.props.style.width).toBe(0);
expect(view).toHaveAnimatedStyle(style);
fireEvent.press(button);
jest.advanceTimersByTime(600);
style.width = 100;
expect(view).toHaveAnimatedStyle(style);
});
});
More examples from react-native-reanimated
repository:
Remarks
- Tests must run with Node 16 or newer.
- If you have custom babel configuration for testing, make sure that Reanimated's babel plugin is enabled in that environment.
Recommended testing library
- @testing-library/react-native
- @testing-library/react-hooks - for dealing with hooks