📜  @testing-library react-native 开关 - Javascript (1)

📅  最后修改于: 2023-12-03 14:38:56.503000             🧑  作者: Mango

@testing-library/react-native Switch


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.

Example
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}
    />
  );
};
Installation

Install @testing-library/react-native using your package manager of choice. For example:

npm install --save-dev @testing-library/react-native
Usage

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);
  });
});
Conclusion

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.