简体   繁体   中英

Jest with React - How do you render an entire component and test it?

Let's say I have a simple App component and I am running a test for it to see if it simply returns a div that prints Hello World to the screen. What is the function helper in order to render App inside my testing file? Furthermore, what is the function to call in the expect call in order to test the HTML being rendered?

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

describe("App", () => {
  it('prints "HELLO WORLD" to the screen', () => {
     expect(**App??**).**toRENDER??**("HELLO WORLD")
  }
}

Thanks

It's a good practice to use enzyme library from airbnb.

There is an example of using both together

Your code can looks like the next:

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import {shallow} from 'enzyme'

describe("App", () => {
  it('prints "HELLO WORLD" to the screen', () => {
     const wrapper = shallow(<App />)

     expect(wrapper.text()).toBe("HELLO WORLD")
  }
}

You would want to look at Jest's snapshot testing for this. This is as simple as calling:

import renderer from 'react-test-renderer';

describe('snapshot testing', () => {
  it('should render App', () => {
    const component = renderer.create(<App />);
    const tree = component.toJSON();
    expect(component).toMatchSnapshot();
  });
});

A snapshot file will be stored in a __tests__/__snapshots__ folder. Make sure you commit these snapshot files into your Git repository so other contributors can have a snapshot to their components against.

For more information on how to setup Jest snapshot testing with React, refer to this docs here as you will need to install some npm dependencies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM