

Custom jest matchers to test the state of React Native
source link: https://reactnativeexample.com/custom-jest-matchers-to-test-the-state-of-react-native/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

jest-native
Custom jest matchers to test the state of React Native.
The problem
You want to use jest to write tests that assert various things
about the state of a React Native app. As part of that goal, you want to avoid all the repetitive
patterns that arise in doing so like checking for a native element's props, its text content, its
styles, and more.
This solution
The jest-native
library provides a set of custom jest matchers that you can use to extend jest.
These will make your tests more declarative, clear to read and to maintain.
Compatibility
These matchers should, for the most part, be agnostic enough to work with any React Native testing
utilities, but they are primarily intended to be used with
RNTL. Any issues raised with existing
matchers or any newly proposed matchers must be viewed through compatibility with that library and
its guiding principles first.
Installation
This module should be installed as one of your project's devDependencies
:
npm install --save-dev @testing-library/jest-native
You will need react-test-renderer
, react
, and react-native
installed in order to use this
package.
Usage
Import @testing-library/jest-native/extend-expect
once (for instance in your
tests setup file) and you're good
to go:
import '@testing-library/jest-native/extend-expect';
Alternatively, you can selectively import only the matchers you intend to use, and extend jest'sexpect
yourself:
import { toBeEmpty, toHaveTextContent } from '@testing-library/jest-native';
expect.extend({ toBeEmpty, toHaveTextContent });
Matchers
jest-native
has only been tested to work with RNTL
. Keep in mind that these queries will only
work on UI elements that bridge to native.
toBeDisabled
toBeDisabled();
Check whether or not an element is disabled from a user perspective.
This matcher will check if the element or its parent has a disabled
prop, or if it has
`accessibilityState={{disabled: true]}.
It also works with accessibilityStates={['disabled']}
for now. However, this prop is deprecated in
React Native 0.62
Examples
const { getByTestId } = render(
<View>
<Button disabled testID="button" title="submit" onPress={e => e} />
<TextInput accessibilityState={{ disabled: true }} testID="input" value="text" />
</View>,
);
expect(getByTestId('button')).toBeDisabled();
expect(getByTestId('input')).toBeDisabled();
toBeEnabled
toBeEnabled();
Check whether or not an element is enabled from a user perspective.
Works similarly to expect().not.toBeDisabled()
.
Examples
const { getByTestId } = render(
<View>
<Button testID="button" title="submit" onPress={e => e} />
<TextInput testID="input" value="text" />
</View>,
);
expect(getByTestId('button')).toBeEnabled();
expect(getByTestId('input')).toBeEnabled();
toBeEmpty
toBeEmpty();
Check that the given element has no content.
Examples
const { getByTestId } = render(<View testID="empty" />);
expect(getByTestId('empty')).toBeEmpty();
toContainElement
toContainElement(element: ReactTestInstance | null);
Check if an element contains another element as a descendant. Again, will only work for native
elements.
Examples
const { queryByTestId } = render(
<View testID="grandparent">
<View testID="parent">
<View testID="child" />
</View>
<Text testID="text-element" />
</View>,
);
const grandparent = queryByTestId('grandparent');
const parent = queryByTestId('parent');
const child = queryByTestId('child');
const textElement = queryByTestId('text-element');
expect(grandparent).toContainElement(parent);
expect(grandparent).toContainElement(child);
expect(grandparent).toContainElement(textElement);
expect(parent).toContainElement(child);
expect(parent).not.toContainElement(grandparent);
toHaveProp
toHaveProp(prop: string, value?: any);
Check that an element has a given prop.
You can optionally check that the attribute has a specific expected value.
Examples
const { queryByTestId } = render(
<View>
<Text allowFontScaling={false} testID="text">
text
</Text>
<Button disabled testID="button" title="ok" />
</View>,
);
expect(queryByTestId('button')).toHaveProp('accessibilityStates', ['disabled']);
expect(queryByTestId('button')).toHaveProp('accessible');
expect(queryByTestId('button')).not.toHaveProp('disabled');
expect(queryByTestId('button')).not.toHaveProp('title', 'ok');
toHaveTextContent
toHaveTextContent(text: string | RegExp, options?: { normalizeWhitespace: boolean });
Check if an element or its children have the supplied text.
This will perform a partial, case-sensitive match when a string match is provided. To perform a
case-insensitive match, you can use a RegExp
with the /i
modifier.
To enforce matching the complete text content, pass a RegExp
.
Examples
const { queryByTestId } = render(<Text testID="count-value">2</Text>);
expect(queryByTestId('count-value')).toHaveTextContent('2');
expect(queryByTestId('count-value')).toHaveTextContent(2);
expect(queryByTestId('count-value')).toHaveTextContent(/2/);
expect(queryByTestId('count-value')).not.toHaveTextContent('21');
toHaveStyle
toHaveStyle(style: object[] | object);
Check if an element has the supplied styles.
You can pass either an object of React Native style properties, or an array of objects with style
properties. You cannot pass properties from a React Native stylesheet.
Examples
const styles = StyleSheet.create({ text: { fontSize: 16 } });
const { queryByText } = render(
<Text
style={[
{ color: 'black', fontWeight: '600', transform: [{ scale: 2 }, { rotate: '45deg' }] },
styles.text,
]}
>
Hello World
</Text>,
);
expect(queryByText('Hello World')).toHaveStyle({ color: 'black', fontWeight: '600', fontSize: 16 });
expect(queryByText('Hello World')).toHaveStyle({ color: 'black' });
expect(queryByText('Hello World')).toHaveStyle({ fontWeight: '600' });
expect(queryByText('Hello World')).toHaveStyle({ fontSize: 16 });
expect(queryByText('Hello World')).toHaveStyle({ transform: [{ scale: 2 }, { rotate: '45deg' }] });
expect(queryByText('Hello World')).toHaveStyle({ transform: [{ rotate: '45deg' }] });
expect(queryByText('Hello World')).toHaveStyle([{ color: 'black' }, { fontWeight: '600' }]);
expect(queryByText('Hello World')).not.toHaveStyle({ color: 'white' });
GitHub
Recommend
-
32
Quickly setup jest for any project and start testing!. Tagged with development, testing, beginners, javascript.
-
11
How to test HTML5 canvas with jest? In this short article you will learn what you need to install in order to prepare a test environment for canvas operations with jest. After finishing the article, you will be ready...
-
8
Retrying e2e test suites with Jest by Andrew Easton At Wealthfront, we pride ourselves on reliable test coverage across our codebases. However...
-
8
Testing React Native apps with JestHow to write unit and e2e tests for React Native apps using Jest in an Nx workspaceIn my previous
-
6
// Tutorial //How to Test a React App with Jest and React Testing LibraryPublished on May 9, 2022By Alyssa Holland
-
5
Test-Driven Infrastructure Development with Pulumi and JestPosted on Monday, Jun 13, 2022When I was a kid growing up in Southern California, there was a phone number you could call to find out what time it was. It was...
-
6
Jest is a popular testing framework, but, unfortunately, it does not come with a new Angular project out of the box. In this article, we will go over how to quickly replace Karm...
-
7
Why Is My Jest Test Suite So Slow? Our team is a couple of mon...
-
6
Cleaner Unit Tests with Custom Matchers
-
7
Moving Angular CLI to Jest and Web Test RunnerOn the Angular team, we believe testing is critical to build highly complex and scalable applications effectively. Testing takes many forms, and “unit tests” foc...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK