如何使用Jest,Enzyme for React-Native模拟单元测试中的事件

时间:2017-02-16 07:50:47

标签: javascript unit-testing react-native jestjs enzyme

我试图弄清楚如何测试" onPress"在React-Native应用程序中使用Jest的事件,这样我就可以确保调用正确的函数。

我浏览了文档和Google,但无法在React-Native中找到解决方案。

我发现这应该适用于具有enzyme的React-Native:

const mockFunc = jest.fn();
const component = mount(<MyComponent onPress={mockFunc} />);
component.simulate('press');
expect(mockFunc).toHaveBeenCalled();

但这不起作用。好像mount似乎不起作用,我得到了这个输出:

  

ReferenceError:未定义文档

我尝试使用shallow,但是当我查看函数的输出时,TouchableOpacity没有得到呈现...而且你已经猜到了它,它没有工作要么。不知道该怎么做。

有没有人找到在React-Native上测试事件的方法?

由于

2 个答案:

答案 0 :(得分:5)

我能够运行您在React Native中的问题所描述的测试。这是我的配置:

的package.json

"scripts": {
  ...
  "test": "node_modules/jest/bin/jest.js",
}

"devDependencies": {
  ...
  "enzyme": "^3.1.0",
  "enzyme-adapter-react-16": "^1.0.1",
  "enzyme-to-json": "^3.1.2",
  "jest": "^21.2.1",
  "jest-enzyme": "^4.0.0",
  "jest-expo": "~21.0.0",
}

"jest": {
  "preset": "jest-expo",
  "setupFiles": [
    "./test/jestSetup.js"
  ],
  "snapshotSerializers": [
    "./node_modules/enzyme-to-json/serializer"
  ]
}

测试/ jestSetup.js

import { configure, shallow, render, mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

configure( { adapter: new Adapter() } )

// enzyme
global.shallow = shallow
global.render = render
global.mount = mount

示例组件:

import React from 'react'
import { Button } from 'react-native'

const CancelButton = ( props ) =>
  <Button
    { ...props }
    onPress={ () => { props.navigation.goBack() } }
    title="Cancel"
  />

export { CancelButton }

示例测试

import React from 'react'
import { CancelButton } from '../CancelButton'

test( 'onPress', () => {
  const goBackFunc = jest.fn()

  const navigation = {
    goBack: goBackFunc,
  }

  const component = shallow(
    <CancelButton
      navigation={ navigation }
    />
  )

  component.simulate( 'press' )
  expect( goBackFunc ).toHaveBeenCalled()
} )

.babelrc

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": ["transform-react-jsx-source"]
    }
  }
}

答案 1 :(得分:5)

您应该使用shallow代替,然后调用.dive()

const mockFunc = jest.fn();
const component = shallow(<MyComponent onPress={mockFunc} />);    
component.dive().simulate('press');
expect(mockFunc).toHaveBeenCalled();