React Native 测试屏幕是否可见开玩笑 @testing-library/react-native @react-navigation/native
React Native Test if screen is visible jest @testing-library/react-native @react-navigation/native
我有以下测试。请参阅评论以了解问题的解释。
describe('Cancel Button', () => {
it('should navigate back to the previous screen', async () => {
let { getByA11yLabel, findByText } = render(<Navigation />);
await findByText('No Activities'); // Verifies the user is on the No Activities screen.
const addButton = getByA11yLabel('Add New Activity');
await fireEvent.press(addButton); // Takes the user to the New Activity screen.
await findByText("New Activity"); // Verifies the user is on the New Activity Screen.
const cancelButton = getByA11yLabel("Cancel"); // Finds cancel button.
await fireEvent.press(cancelButton); // Clicks cancel button. Currently this button does nothing. It's onPress event does nothing.
await findByText("No Activities"); // Verify the user is on the No Activities screen. I would expect this to fail as the cancel button does not return the user to the previous screen.
})
});
取消按钮目前没有任何作用。
我希望测试失败,因为用户没有返回到“无活动”屏幕。
它目前通过了,因为 findByText 仍然 returns No Activities 元素,即使它所在的屏幕不可见。
我应该如何编写此测试才能使其失败?如何正确检查“无活动”屏幕是否可见?
我发现您可以使用 useIsFocused() 挂钩,然后根据 isFocused 值设置 testID。有人知道这是否会产生不必要的开销吗?
import { useIsFocused, useNavigation } from '@react-navigation/native';
...
const isFocused = useIsFocused();
...
<View testID={isFocused ? 'ActivityDetailsScreen' : 'ActivityDetailsScreenHidden'}>
我有以下测试。请参阅评论以了解问题的解释。
describe('Cancel Button', () => {
it('should navigate back to the previous screen', async () => {
let { getByA11yLabel, findByText } = render(<Navigation />);
await findByText('No Activities'); // Verifies the user is on the No Activities screen.
const addButton = getByA11yLabel('Add New Activity');
await fireEvent.press(addButton); // Takes the user to the New Activity screen.
await findByText("New Activity"); // Verifies the user is on the New Activity Screen.
const cancelButton = getByA11yLabel("Cancel"); // Finds cancel button.
await fireEvent.press(cancelButton); // Clicks cancel button. Currently this button does nothing. It's onPress event does nothing.
await findByText("No Activities"); // Verify the user is on the No Activities screen. I would expect this to fail as the cancel button does not return the user to the previous screen.
})
});
取消按钮目前没有任何作用。 我希望测试失败,因为用户没有返回到“无活动”屏幕。 它目前通过了,因为 findByText 仍然 returns No Activities 元素,即使它所在的屏幕不可见。
我应该如何编写此测试才能使其失败?如何正确检查“无活动”屏幕是否可见?
我发现您可以使用 useIsFocused() 挂钩,然后根据 isFocused 值设置 testID。有人知道这是否会产生不必要的开销吗?
import { useIsFocused, useNavigation } from '@react-navigation/native';
...
const isFocused = useIsFocused();
...
<View testID={isFocused ? 'ActivityDetailsScreen' : 'ActivityDetailsScreenHidden'}>