如何在 React Native 测试中使用 Testing Library 获取组件状态值
在 testing-library/react-native 模块中,可以使用 render 函数渲染 React 组件,并通过查询器获取组件的状态值。
以下是一个示例:
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
const MyComponent = () => {
const [count, setCount] = useState(0);
return (
<View>
<Text>Count: {count}</Text>
<Button title='Increment' onPress={() => setCount(count + 1)} />
</View>
);
};
// 在测试中获取状态值
test('renders count correctly', () => {
const { getByText } = render(<MyComponent />);
const countText = getByText(/Count:/);
expect(countText.props.children).toBe('Count: 0');
});
在上面的示例中,我们使用 render 函数渲染了一个 MyComponent 组件,并通过 getByText 查询器获取了显示计数的 Text 组件。然后,我们可以通过 countText.props.children 来获取 Text 组件的内容,并进行断言验证。
可以使用其他查询器,如 getByTestId、getByLabelText 等,根据组件的特定属性或标签来获取组件。然后,通过查询器返回的组件对象,可以获取其状态值或其他属性值来进行断言验证。
原文地址: https://www.cveoy.top/t/topic/fL00 著作权归作者所有。请勿转载和采集!