当我运行测试时,得到“不变违反:本机模块不能为空”。

时间:2018-12-21 05:40:00

标签: javascript reactjs react-native jestjs enzyme

我在下面有一个Login组件,并且正在为该组件编写一些测试用例。当我尝试运行测试时,出现以下错误。

测试

import renderer from 'react-test-renderer'

import Login from '../Login'
let props, wrapper

beforeEach(() => {
  props = {
    loginAttempt: jest.fn(),
    recoverAttempt: jest.fn(),
    reset: jest.fn()
  }
  wrapper = shallow(<Login {...props} />)
})

describe('tests for <Login />', () => {
  test('should have a formProvider with handlesubmit atribute', () => {
    const value = wrapper.find('FormProvider')
    expect(value.length).toBe(1)
  })
})

//Snapshot test
test('Snapshot test for the Contact form', () => {
  const tree = renderer.create(<Login {...props} />).toJSON()
  expect(tree).toMatchSnapshot()
})

组件

import React, { Component } from 'react'
import KeyboardAvoidingWrapper from 'components/Wrappers/KeyboardAvoidingWrapper'

export default class AuthScreen extends Component {
  state = {

  }

  toggleRecovery = e => {

    )
  }

  loginAttempt = data => {

  }

  recoverAttempt = data => {

  }

  componentWillUnmount() {

  }

  render() {
    let { loginAttempt, toggleRecovery, recoverAttempt, state, props } = this
    let { recovery } = state
    let { error, fetching } = props
    return (
      <KeyboardAvoidingWrapper enabled={false} behavior="padding" fluid>

    UI GOES HERE..

      </KeyboardAvoidingWrapper>
    )
  }
}

错误

  ● Test suite failed to run

    Invariant Violation: Native module cannot be null.

      at invariant (node_modules/react-native/node_modules/fbjs/lib/invariant.js:40:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:36:36)
      at Object.<anonymous> (node_modules/react-native-safari-view/SafariViewManager.ios.js:12:20)
      at Object.<anonymous> (node_modules/react-native-safari-view/index.js:1:238)

为什么我遇到此错误。是因为该组件未正确导入。我不知道为什么会这样,我怎么解决这个问题。

谢谢

1 个答案:

答案 0 :(得分:1)

当您在渲染树中导入本机组件时会发生此问题,因为测试渲染器没有它们。要解决此问题,您需要模拟组件(https://jestjs.io/docs/en/manual-mocks),或使用浅层渲染(https://reactjs.org/docs/shallow-renderer.html

对于您的特殊情况,这是可以帮助您的github问题:https://github.com/naoufal/react-native-safari-view/issues/99

另一个解决方案可能是使用react-native-mock-render模块(react-native-mock最活跃的分支)