首页 > 解决方案 > 如何在 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)"
    ],
  }

标签: javascriptreactjsreact-nativejestjsexpo

解决方案


我能够用这段代码解决这个问题

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 {...{

推荐阅读