What is 1 Enzyme?

Enzyme is a type of macromolecule biocatalyst. Enzymes speed up chemical reactions (i.e. catalyze them) – Wikipedia

Airbnb’s open source React test library Enzyme provides a set of simple and powerful APIS and DOM processing in a jquery-style way, making the development experience very friendly. Not only was it popular in the open source community, it was also featured by React. – an IO

The former Enzyme is an Enzyme that helps to create a better Enzyme. So what is the chemical ๐ŸŽฟ reaction with Jest in the React component test?


2. Prepare before class

2.1 the project

Here we use create-react-app to initialize a project

npm i -g create-react-app
npx create-react-app enzyme-in-action --use-npm
cd enzyme-in-action
npm start 
Copy the code

The browser will automatically open and you’ll see this page.

create-react-app
Create a New React App — React

2.2 Preparing jest and Enzyme configurations

Modify scripts in ::package.json::

- "test": "react-scripts test",
+ "test": "jest",
Copy the code

Add jest configuration to ::package.json::

"jest": { "transform": { "^.+\\.jsx? $": "babel-jest", "^.+\\.svg$": "jest-svg-transformer" }, "moduleNameMapper": { "\\.(css|less)$": "identity-obj-proxy" } }Copy the code

Installing dependency packages

npm i -D jest babel-jest babel-core babel-preset-env babel-preset-react enzyme enzyme-adapter-react-16 jest-svg-transformer identity-obj-proxy
Copy the code

Jest-svg-transformer and identit-obj-proxy are used to ensure that the import logo from ‘./logo.svg’ import ‘./ app.css ‘in JSX files is rendered properly

2.3 Background

  1. EnzymeIt provides three test methods:
    • ::shallow::
    • ::render::
    • ::mount::
  2. wrapperWrapper is a class wrapped by enzyme to be used by the API
  3. shallowDuring unit testing, shallow rendering renders a component as a virtual DOM object without rendering its internal child components, and is not really a complete React Render that can’t interact with its child components.

3 hands type

Modify create-react-app to generate :: SRC/app.test.js ::

import React from 'react'
import App from './App'
import { configure, shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

configure({ adapter: new Adapter() })

describe(`<App />`, () => {
  it('should render App', () = > {const warpper = shallow(<App />)
    console.log(warpper.debug())
  })
})
Copy the code

npm run test

warpper.debug()
warpper


4 findTest nodes

Add to ::app.js::

  <img src={logo} className="App-logo" alt="logo" />
+ <h1>Welcome to React</h1>
  <p>
Copy the code

Now let’s officially write single test ::app.test.js::

describe('Test 
      ', () = > {const warpper = shallow(<App />) it (' 1. Contains a p tag, () = > {expect (warpper. Find (" p "). The length), place (1)}) it (' 2. Class for "App - link" element can be rendered normally ', () => {expect(warpper.find('.app-link ').exists()).tobetruthy ()}) it('3. () => {expect(warpper.find('header').hasclass (' app-header ')).tobetruthy ()}) it('4. () => { expect(warpper.find('header').children().length).toBe(4) }) it('5. Test the content of the H1 tags', () = > {expect (warpper. Find (' H1). The text ()). The place (' Welcome to React ')}) it (' 6. Class ', () => {expect(warpper.find({Alt: 'logo'}).hasClass(' app-logo ')).tobetruthy ()})Copy the code

Are you familiar with jQuery? There is no more explanation here.

The recommended VsCode plugin Jest will have an icon in front of each unit test to indicate whether the current test is overtested.


5 usingsnapshotsThe test component

Jest provides a snapshot of how many unit tests need to be written to test components as found does. Install dependencies:

npm i -D enzyme-to-json
Copy the code

Add tests to ::app.test.js::

  import Adapter from 'enzyme-adapter-react-16'
+ import toJson from 'enzyme-to-json'
Copy the code
describe('test 
       snapshots', () = > {const tree = shallow(<App />) it (' 1. Match the snapshot, () = > {expect (toJson (tree). ToMatchSnapshot ()})})Copy the code

NPM run test is available on the command line

1 Snapshot Written from 1test suite.
Copy the code

src/__snapshots__/App.test.js.snap
enzyme-to-json

Is created when toMatchSnapshot is first written. It is updated when we modify the test. Let’s try modifying the React component and see what happens

Modify: : app. Js: :

- <h1>Welcome to React</h1>
+ <h1>Welcome to React Jest Enzyme</h1>
Copy the code

NPM run test has an error message on the command line telling you what has changed

Jest –updateSnapshot in the case of watch, press u to update the snapshot. If you are using vscode, it will remind you whether to update the component.

6 Test the components that contain props

First add a component :: app.js ::

export class Link extends PureComponent {
  render() {
    const { hide, address } = this.props
    return hide ? null : <a href={address}>Click</a>}}Copy the code

Add tests to ::app.test.js::

describe('Test 
      ', () => {
  it('1. Test link component ', () = > {const warpper = shallow(<Link address="https://www.google.com" />) expect(warpper.props().href).toBe('https://www.google.com') }) it('2. () => {const warpper = shallow()<Link />)
    expect(warpper.find('a').length).toBe(1)
    warpper.setProps({ hide: true })
    expect(warpper.find('a').length).toBe(0)
  })
})
Copy the code
  1. warpper.props()As the result of the
{ href: 'https://www.google.com', children: 'Click' }
Copy the code
  1. In the case:2. Test the Link propsusingwarpper.setProps()Dynamic to<Link />Set parameters to verify that the component is properly rendered

X to be continued…

How to test state, life cycle, etc. Jest didn’t write as much as I liked, so I will sort out an advanced article. For some people who are not clear about integration testing and unit testing, I will sort out an article related to Cypress. Autumn Beijing weekend, began to haze, weekend to accompany Zhou teacher preparation for the senior teacher qualification certificate, to sit in front of the computer to write for such a long time.

Eight years have passed since I came to Beijing at the end of 2010. When I first came to Beijing, I was ignorant but fearless. Now I am tasteless and helpless. Mark this moment of mixed emotions. Look after no matter where, calm to right. Oh — Today’s Diary of Fun is from ๐Ÿ’ฝ Air Coincided ใƒˆ ยท Jin-Oh. It’s late and full of energy and I’m writing a third one.

The technical ability is limited, what improper place please correct. If you have any doubts about the front end ๐Ÿค”, you can leave a message and communicate, and you will put it into the writing plan behind.