Jest和React Native中的模拟平台检测 [英] Mocking platform detection in Jest and React Native

查看:79
本文介绍了Jest和React Native中的模拟平台检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试测试的某些代码使用以下方式检测到平台:

Some of the code I am trying to test detects the platform, using, e.g.:

import { Platform } from 'react-native';
...

if (Platform.OS === 'android') {
  ...
} else {
  ...
}

是否有一种明智的方法可以用Jest和/或其他方法来模拟它,所以我可以在一个测试运行中测试两个分支?

Is there a sensible way to mock this with Jest and/or something else, so I can test both branches in one test run?

还是将其解耦并将平台放入例如上下文变量的明智方法?尽管总觉得重组代码以使其更易于测试是一种欺骗.

Or is the smart way to decouple it and put the platform into, e.g., a context variable? Although it always feels restructuring code to make it easier to test is something of a cheat.

推荐答案

这对我有效(Jest 21.2.1,酶3.2.0):

jest.mock('Platform', () => {
    const Platform = require.requireActual('Platform');
    Platform.OS = 'android';
    return Platform;
});

将其放在测试的顶部或 a <例如c2> .

Put it either at the top of your test, or in a beforeAll for example.

这篇关于Jest和React Native中的模拟平台检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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