如何使用 Jest 在 React Native 中测试 Alert [英] How to test Alert in React Native with Jest

查看:29
本文介绍了如何使用 Jest 在 React Native 中测试 Alert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在我的程序中,当用户登录时,如果所有凭据都正确,如果缺少任何详细信息或格式不正确,他们将进入下一页,并且屏幕上会显示警报.

So in my program, when a user logs in, if all credentials are correct they will proceed to the next page if any details are missing or incorrect format, and alert is shown on screen.

如果按下按钮后显示警报,我如何在 React Native 中使用 Jest 进行测试,并确认警报文本是否正确?

How do I test using Jest in React Native if the alert has been displayed after a button press, and confirm that the text of the alert is correct?

我的一些组件如下所示:

Some of my component is shown below:

...
.catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    alert(errorMessage)
  });

错误文本是由 Google 的 Firebase 生成的,但我知道它是什么.

The error text is generated by Google's Firebase, but I do know what it is.

推荐答案

假设你正在使用 react-native 的 Alert 并且自己调用它,你可以像这样窥探它:

Assuming you are using react-native's Alert and calling it yourself, you can spy on it like so:

import { Alert } from 'react-native';

jest.spyOn(Alert, 'alert');

然后您可以检查它是否已被调用,以及使用了哪些参数:

You can then check that it has been called, and what arguments were used:

expect(Alert.alert).toHaveBeenCalledWith(errorMessageText)

这篇关于如何使用 Jest 在 React Native 中测试 Alert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆