Jest 和 React Native 中的模拟平台检测 [英] Mocking platform detection in Jest and React Native
本文介绍了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, Enzyme 3.2.0):
jest.mock('Platform', () => {
const Platform = require.requireActual('Platform');
Platform.OS = 'android';
return Platform;
});
将它放在测试的顶部,或者放在 a <代码>beforeAll 例如.
Put it either at the top of your test, or in a beforeAll
for example.
这篇关于Jest 和 React Native 中的模拟平台检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文