Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
@testing-library/jest-native
Advanced tools
@testing-library/jest-native is a set of custom jest matchers to test the state of React Native components. It extends jest-dom to provide more specific matchers for React Native components, making it easier to write tests that are more readable and maintainable.
toHaveTextContent
This matcher checks if a React Native component contains the specified text content. It is useful for verifying that text elements render the correct content.
expect(element).toHaveTextContent('Hello World')
toBeDisabled
This matcher checks if a button or other interactive element is disabled. It helps ensure that the UI behaves correctly based on the component's state.
expect(button).toBeDisabled()
toHaveStyle
This matcher checks if a component has the specified style properties. It is useful for verifying that styles are applied correctly to components.
expect(element).toHaveStyle({ color: 'red' })
toBeVisible
This matcher checks if a component is visible in the UI. It helps ensure that elements are rendered and visible to the user as expected.
expect(element).toBeVisible()
jest-dom provides custom jest matchers to test the state of the DOM. While it is primarily designed for web applications, it offers similar functionality to @testing-library/jest-native for testing the state of DOM elements. However, it does not provide matchers specific to React Native components.
react-native-testing-library is a lightweight solution for testing React Native components. It provides utilities to render components and query elements, similar to @testing-library/react. While it does not offer custom jest matchers like @testing-library/jest-native, it is often used in conjunction with it to provide a comprehensive testing solution for React Native applications.
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.
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.
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.
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.
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's
expect
yourself:
import { toBeEmpty, toHaveTextContent } from '@testing-library/jest-native';
expect.extend({ toBeEmpty, toHaveTextContent });
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
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()
.
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.
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.
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. Only works for native elements, so this is similar to checking for attributes in the DOM.
You can optionally check that the attribute has a specific expected value.
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 has 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
.
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.
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' });
This library was made to be a companion for RNTL.
It was inspired by jest-dom, the companion library for DTL. We emulated as many of those helpers as we could while keeping in mind the guiding principles.
None known, you can add the first!
Thanks goes to these wonderful people (emoji key):
Brandon Carroll 💻 📖 🚇 ⚠️ | Santi 💻 | Marnus Weststrate 💻 | Matthieu Harlé 💻 | Alvaro Catalina 💻 | ilker Yılmaz 📖 | Donovan Hiland 💻 ⚠️ |
This project follows the all-contributors specification. Contributions of any kind welcome!
FAQs
Custom jest matchers to test the state of React Native
We found that @testing-library/jest-native demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 15 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.