如何在Jest测试中模拟StatusBarManager.getHeight?

时间:2019-09-02 10:12:17

标签: javascript reactjs react-native jestjs expo

我正在使用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)"
    ],
  }

1 个答案:

答案 0 :(得分:0)

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

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