How to mock StatusBarManager.getHeight in Jest test?

妖精的绣舞 提交于 2020-01-25 08:16:08

问题


I'm using expo 34 and react-native-ui-lib from wix and have a problem to setup jest tests for my components. The problem looks to appear in link of the wix library

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 is not a function

TypeError: StatusBarManager.getHeight is not a function If I simply change it and return 42 my test can run.

Is it any way to mock StatusBarManager.getHeight in jest?

I've tried to create jest-setup.js in my root folder

import { NativeModules } from 'react-native';

NativeModules.StatusBarManager = {getHeight: jest.fn()};

// mock native modules
jest.mock('@react-native-community/blur', () => {});

But it didn't work. My current 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)"
    ],
  }

回答1:


I was able to solve this problem with this code

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


来源:https://stackoverflow.com/questions/57755131/how-to-mock-statusbarmanager-getheight-in-jest-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!