【问题标题】:How to mock StatusBarManager.getHeight in Jest test?如何在 Jest 测试中模拟 StatusBarManager.getHeight?
【发布时间】:2020-01-05 09:12:56
【问题描述】:

我正在使用来自 wix 的 expo 34 和 react-native-ui-lib 并且在为我的组件设置笑话测试时遇到问题。问题似乎出现在 wix 库的link

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 不是函数 如果我只是更改它并返回 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)"
    ],
  }

【问题讨论】:

    标签: javascript reactjs react-native jestjs expo


    【解决方案1】:

    我可以用这段代码解决这个问题

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

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 1970-01-01
      • 2023-02-12
      • 1970-01-01
      • 2018-04-25
      • 2018-12-15
      • 2020-12-24
      • 2020-05-28
      • 1970-01-01
      相关资源
      最近更新 更多