You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jest测试React Native中PIN不匹配时Toast消息的显示?

验证React Native中PIN不匹配时Toast的提示消息

问题场景

我正在用Jest测试React Native应用,需要验证当PIN不匹配时,Toast是否显示指定的"invalid answer"消息。

业务代码中触发Toast的逻辑:

if (pinMismatch) {
       Toast.show({
              type: "error",
              text1: "invalid answer",
       });
}

测试用例框架:

it('handles unsuccessful registration due to PIN mismatch', async () => {
    const { getByText, getByTestId } = render(
                <NavigationContainer>
                           <Registration navigation={mockNavigation} />
                </NavigationContainer>
          );

    fireEvent.changeText(getByTestId('pin'), '123456');
    fireEvent.changeText(getByTestId('confirm-pin'), '654321');
    const registrationButton = getByText("register");
    fireEvent.press(registrationButton);

    await waitFor(() => {
             // 我需要在此处验证"invalid answer"已显示
    })
})

实现方案

根据你使用的Toast类型,选择对应验证方式:

方案1:Mock第三方Toast库(如react-native-toast-message)

如果使用第三方Toast库,直接mock其show方法并断言调用参数:

  1. 在测试文件顶部mock Toast模块:
jest.mock('react-native-toast-message', () => ({
  show: jest.fn(),
}));
  1. 在waitFor中添加断言:
import Toast from 'react-native-toast-message';

// ... 测试用例其余代码 ...

await waitFor(() => {
  expect(Toast.show).toHaveBeenCalledWith(expect.objectContaining({
    type: "error",
    text1: "invalid answer",
  }));
});

方案2:自定义Toast组件(带测试ID)

如果是自定义Toast组件,给文本元素添加testID后直接查询断言:

  1. 自定义Toast组件中添加测试ID:
// 示例自定义Toast组件
const CustomToast = ({ text1 }) => (
  <View>
    <Text testID="toast-text1">{text1}</Text>
  </View>
);
  1. 在测试用例中验证:
await waitFor(() => {
  const toastText = getByTestId('toast-text1');
  expect(toastText).toHaveTextContent('invalid answer');
});

内容的提问来源于stack exchange,提问作者olulu26

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 21:25:57