Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a children text component with Jest & Enzyme

I'm writing the test suite of my React Native application and I was wondering how to test the shallow rendering of a React Native child component with Jest & Enzyme.

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)
    })
  })
})

The previous code gives this error, Jest doesn't find the children prop.

Expected: "Test button"
Received: undefined
like image 694
Théo Lavaux Avatar asked Jun 13 '19 11:06

Théo Lavaux


1 Answers

I think you just need to test the text of your component (and not its props), try with:

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

like image 51
Dario Avatar answered Sep 26 '22 22:09

Dario