javascript - 如何在 Jest 测试中模拟 StatusBarManager.getHeight?
问题描述
我正在使用来自 wix 的 expo 34 和react-native-ui-lib,并且在为我的组件设置玩笑测试时遇到问题。问题似乎出现在wix 库的链接中
function setStatusBarHeight() {
statusBarHeight = isIOS ? 20 : StatusBarManager.HEIGHT;
if (isIOS) {
// override guesstimate height with the actual height from StatusBarManager
StatusBarManager.getHeight(data => (statusBarHeight = data.height));
}
}
TypeError:StatusBarManager.getHeight 不是函数
TypeError: StatusBarManager.getHeight is not a function 如果我只是更改它并返回 42 我的测试可以运行。
有什么办法可以StatusBarManager.getHeight
开玩笑吗?
我试图jest-setup.js
在我的根文件夹中创建
import { NativeModules } from 'react-native';
NativeModules.StatusBarManager = {getHeight: jest.fn()};
// mock native modules
jest.mock('@react-native-community/blur', () => {});
但它没有用。我现在的jest.config.js
module.exports = {
preset: "jest-expo",
moduleFileExtensions: ['js','jsx','json', 'ts', 'tsx'],
transform: {
"^.+\\.(js|jsx|ts|tsx)$": "babel-jest"
},
testMatch: [
"**/*.test.ts?(x)"
],
}
解决方案
我能够用这段代码解决这个问题
import React from 'react'
import 'react-native'
import { NativeModules } from 'react-native' // !this module
import renderer from 'react-test-renderer'
import Description from './Description'
// and this mock
NativeModules.StatusBarManager = {getHeight: jest.fn()}
describe('TextArea test', () => {
it('Empty TextArea with title', () => {
const description = renderer.create(
<Description {...{
推荐阅读
- tensorflow - 在一个环境中安装了 tensorflow,现在导入不起作用
- r - 访问函数内的全局变量
- python - 创建 10 个列表并在一个循环中分配每 10 个值
- java - @ConditionalOnBean 不适用于 JdbcTemplate.class
- java - 解压文件后删除目录
- php - 从多维数组 PHP 中获取数据
- javascript - 将数组中的对象合并为一个
- vuejs2 - 从另一个组件调用的 vue.js 2 混合函数,给出“TypeError:无法读取未定义的属性‘搜索’”
- redux - 从 redux-observable 中调度多个动作
- sql - 我需要一个包含列 CatId 和 Flag 的视图。如果存在 CatID 的任何子类别,则标志将为 1