📅  最后修改于: 2023-12-03 14:38:56.503000             🧑  作者: Mango
The @testing-library/react-native
library provides a set of utilities to test React Native components that follows good practices and makes it easy to write maintainable and readable tests.
One of the components that can be tested using this library is the Switch
, which is a UI component that represents a binary on/off switch.
This guide will cover the basics of how to test a Switch
component using @testing-library/react-native
.
import React, { useState } from 'react';
import { Switch } from 'react-native';
const MySwitch = () => {
const [value, setValue] = useState(false);
const toggleSwitch = () => {
setValue(previousState => !previousState);
};
return (
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={value ? "#f5dd4b" : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={value}
/>
);
};
Install @testing-library/react-native
using your package manager of choice. For example:
npm install --save-dev @testing-library/react-native
To test a Switch
component, you can use the render
function from @testing-library/react-native
to render the component and get a reference to its elements. Then, you can use the fireEvent
function to simulate interactions with the component and test the results.
import React from 'react';
import { fireEvent, render } from '@testing-library/react-native';
import MySwitch from './MySwitch';
describe('MySwitch component', () => {
it('toggles value when pressed', () => {
const { getByRole } = render(<MySwitch />);
const switchElement = getByRole('switch');
expect(switchElement.props.value).toBe(false);
fireEvent.press(switchElement);
expect(switchElement.props.value).toBe(true);
fireEvent.press(switchElement);
expect(switchElement.props.value).toBe(false);
});
});
Testing components is an important part of ensuring the quality of your application. @testing-library/react-native
makes it easy to write maintainable and readable tests by providing a set of utilities that follow good practices.
In this guide, we saw how to test a Switch
component using @testing-library/react-native
. You can use the same approach to test other components in your application.