如何使用Jest&Enzyme测试儿童文本组件

时间:2019-06-13 11:42:00

标签: reactjs react-native jestjs enzyme

我正在编写React Native应用程序的测试套件,我想知道如何使用Jest&Enzyme测试React Native子组件的浅层渲染。

import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import React from 'react'

import NextButton from './NextButton'

describe('NextButton component', () => {
  describe('Rendering', () => {
    let onPress, text, wrapper

    beforeEach(() => {
      onPress = jest.fn()
      text = 'Test button'
      wrapper = shallow(<NextButton onPress={onPress}>{text}</NextButton>)
    })

    test('should render NextButton correctly', () => {
      expect(toJson(wrapper)).toMatchSnapshot()
    })

    test('should have text rendered as a child', () => {
      expect(toJson(wrapper.prop('children'))).toEqual(text)
    })
  })
})

先前的代码给出了此错误,Jest没有找到children道具。

Expected: "Test button"
Received: undefined

1 个答案:

答案 0 :(得分:1)

我认为您只需要测试组件的text(而不是其道具),请尝试:

expect(wrapper.text()).toEqual(text);