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

Thé*_*aux 4 reactjs jestjs react-native 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)
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

前面的代码给出了这个错误,Jest 没有找到children道具。

Expected: "Test button"
Received: undefined
Run Code Online (Sandbox Code Playgroud)

Dar*_*rio 9

我认为你只需要测试text你的组件(而不是它的道具),试试:

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