【前端單元測試入門02】react的單元測試之Enzyme


React項目的單元測試

React的組件結構和JSX語法,對上一章的內容來講進行測試顯得很勉強。
React官方已經提供了一個測試工具庫:react-dom/test-utils
只是用起來不夠方便,於是有了一些第三方的封裝庫,比如Airbnb公司的Enzyme

測試項目的配置

本次測試項目是根據上一章的測試項目衍生而來,包含上一章講到的Mocha和chai,這里只介紹新加的一些模塊。
項目結構圖如下:
測試項目結構圖

因為是React項目,所以自然需要安裝React的一些東西:

npm install --save react react-dom babel-preset-react

然后.babelrc文件內容改為

{
  "presets": [ "es2015","react" ]
}

example.jsx的內容為:

import React from 'react'

const Example=(props)=>{
    return (<div>
            <button>{props.text}</button>
        </div>)
}
export default Example

example.test.js的內容暫時為空

Enzyme 的安裝與配置

npm install --save-dev enzyme

而enzyme還需要根據React的版本安裝適配器,適配器對應表如下:

Enzyme Adapter Package React semver compatibility
enzyme-adapter-react-16 ^16.0.0
enzyme-adapter-react-15 ^15.5.0
enzyme-adapter-react-15.4 15.0.0-0 - 15.4.x
enzyme-adapter-react-14 ^0.14.0
enzyme-adapter-react-13 ^0.13.0

那么因為我們安裝的React版本為^16.2.0
所以需要安裝:

npm install --save-dev enzyme-adapter-react-16

Enzyme 的使用

現在開始用Enzyme為example.jsx編寫測試代碼:

import {assert} from 'chai'
import React from 'react'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import Example from '../src/example'

const {shallow}=Enzyme

Enzyme.configure({ adapter: new Adapter() })

describe('Enzyme的淺渲染測試套件', function () {
  it('Example組件中按鈕的名字為text的值', function () {
    const name='按鈕名'
    let app = shallow(<Example text={name} />)
    assert.equal(app.find('button').text(),name)
  })
})

如上面代碼所示,在使用Enzyme 前需要先適配React對應的版本

Enzyme.configure({ adapter: new Adapter() })

而為了避免每個測試文件都這么寫,可以再test目錄下新建一個配置文件:

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({
  adapter: new Adapter(),
});

export default Enzyme;

然后測試文件的時候只需要引用這個配置文件即可:

import {assert} from 'chai'
import React from 'react'
import Enzyme from './config/Enzyme.config';
import Example from '../src/example'

const {shallow}=Enzyme

describe('Enzyme的淺渲染測試套件', function () {
  it('Example組件中按鈕的名字為text的值', function () {
    const name='按鈕名'
    let app = shallow(<Example text={name} />)
    assert.equal(app.find('button').text(),name)
  })
})

Enzyme 的使用之淺渲染shallow

上面的例子中就用到淺渲染shallow 。
Shallow Rendering(淺渲染)指的是,將一個組件渲染成虛擬DOM對象,但是只渲染第一層,不渲染所有子組件,所以處理速度非常快。它不需要DOM環境,因為根本沒有加載進DOM。
shallow的函數輸入組件,返回組件的淺渲染結果,而返回的結果可以用類似jquery的形式獲取組件的信息。
運行

npm test 

也就是:

mocha --require babel-core/register

得到以下結果:
淺渲染測試運行結果

淺渲染測試與子組件的相關的代碼:

現在修改我們的例子,新加一個sub.jsx:

import React from 'react'

const Sub=(props)=>{
    return (<span>{props.text}</span>)
}
export default Sub

在原來的example.jsx中使用Sub,形成嵌套:

import React from 'react'
import Sub from './sub'

const Example=(props)=>{
    return (<div>
            <button>{props.text}</button>
            <Sub text={props.text}  />
        </div>)
}
export default Example

使用shadow測試子組件的代碼:

import {assert} from 'chai'
import React from 'react'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import Example from '../src/example'

const {shallow,mount}=Enzyme

Enzyme.configure({ adapter: new Adapter() })

describe('Enzyme shallow的淺渲染(Shallow Rendering)中', function () {
  it('Example組件中按鈕的名字為子組件Sub中span的值', function () {
    const name='按鈕名'
    let app = shallow(<Example text={name} />)
    const buttonObj=app.find('button')
    const spanObj=app.find('span')

    console.info(`查找到button的個數:${buttonObj.length}`)
    console.info(`查找到span的個數:${spanObj.length}`)

    assert.equal(buttonObj.text(),spanObj.text())
  })
})

測試結果為:
淺渲染測試子組件的結果

如上圖所示,shallow所得到的淺渲染對象中差找不到子組件Sub的span元素。
為了解決上面這種情況,Enzyme給出的解決方案為用mount實現 Full DOM Rendering

Enzyme 的使用之mount

mount方法用於將React組件加載為真實DOM節點。
然而真實DOM需要一個瀏覽器環境,為了解決這個問題,我們可以用到jsdom.
下面是jsdom的官方介紹:

jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG DOM and HTML Standards, for use with Node.js. In general, the goal of the project is to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications.

也就是說我們可以用jsdom模擬一個瀏覽器環境去加載真實的DOM節點。
首先安裝jsdom:

npm install --save-dev jsdom

然后在test目錄下新建一個文件setup.js:

import jsdom from 'jsdom';
const { JSDOM } = jsdom;

if (typeof document === 'undefined') {
    const dom=new JSDOM('<!doctype html><html><head></head><body></body></html>');
    global.window =dom.window;
    global.document = global.window.document;
    global.navigator = global.window.navigator;
}

最后修改我們的package.json中的測試腳本為:

 "scripts": {
    "test": "mocha --require babel-core/register --require ./test/setup.js"
  }

這樣在運行npm test時,會先用babel解析js,然后再執行setup.js中的代碼,給global對象模擬一個瀏覽器環境。

在配置好模擬瀏覽器環境后,修改測試代碼為:

import {assert} from 'chai'
import React from 'react'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import Example from '../src/example'

const {shallow,mount}=Enzyme

Enzyme.configure({ adapter: new Adapter() })

describe('Enzyme mount的DOM渲染(Full DOM Rendering)中', function () {
  it('Example組件中按鈕的名字為子組件Sub中span的值', function () {
    const name='按鈕名'
    let app = mount(<Example text={name} />)

    const buttonObj=app.find('button')
    const spanObj=app.find('span')

    console.info(`查找到button的個數:${buttonObj.length}`)
    console.info(`查找到span的個數:${spanObj.length}`)

    assert.equal(buttonObj.text(),spanObj.text())
  })
})

運行

npm test

結果為:

mount的Full DOM Rendering測試結果

如上,在mount得到的結果中可以找到子組件的元素

Enzyme 的使用之render

而Enzyme還提供了一個不需要jsdom模擬環境解決子組件測試的方法:render
Enzyme的render函數得到的結果被稱為Static Rendered Markup,以下為官方的介紹

enzyme's render function is used to render react components to static HTML and analyze the resulting HTML structure.
render returns a wrapper very similar to the other renderers in enzyme, mount and shallow; however, render uses a third party HTML parsing and traversal library Cheerio. We believe that Cheerio handles parsing and traversing HTML extremely well, and duplicating this functionality ourselves would be a disservice.

意思就是說render會根據react組件得到一個靜態HTML文本結果,借助一個第三方的HTML解析庫Cheerio去生成一個類似於mount和shallow得到的封裝對象。

修改測試代碼為:

import {assert} from 'chai'
import React from 'react'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import Example from '../src/example'

const {shallow,mount,render}=Enzyme

Enzyme.configure({ adapter: new Adapter() })

describe('Enzyme render的靜態HTML渲染(Static Rendered Markup)中', function () {
  it('Example組件中按鈕的名字為子組件Sub中span的值', function () {
    const name='按鈕名'
    let app = render(<Example text={name} />)

    const buttonObj=app.find('button')
    const spanObj=app.find('span')

    console.info(`查找到button的個數:${buttonObj.length}`)
    console.info(`查找到span的個數:${spanObj.length}`)

    assert.equal(buttonObj.text(),spanObj.text())
  })
})

測試結果為:

render測試結果

shallow ,render和mount的效率對比

空口無憑,直接上測試代碼:

it('測試 shallow 500次', () => {
  for (let i = 0; i < 500; i++) {
    const nav = shallow(<Nav />)
    assert.equal(nav.find('a').text(), '首頁')
  }
})

it('測試render500次', () => {
  for (let i = 0; i < 500; i++) {
    const nav = render(<Nav />)
    assert.equal(nav.find('a').text(), '首頁')
  }
})

it('測試mount500次', () => {
  for (let i = 0; i < 500; i++) {
    const nav = mount(<Nav />)
    assert.equal(nav.find('a').text(), '首頁')
  }
})

結果:

shallow測試結果

render測試結果

mount測試結果

結果證明:
shallow果然最快,這是肯定的,但是因為shallow的局限性,我們可能更想知道render和mount的效率。
事實證明,render的效率是mount的兩倍。
有人可能要質疑你為什么不將次數弄更大一點,因為在設定為1000次的情況下mount直接超時了,也就是超過了mocha的默認執行時間限定2000ms。
那么問題來了,mount存在的價值是什么,render就可以測試子組件,render還不需要jsdom和額外的配置。
當然是有價值的,shallow和mount因為都是dom對象的緣故,所以都是可以模擬交互的,比如

 const nav = mount(<Nav />)
 nav.find('a').simulate('click')

而render是不能的。

小結

簡而言之,Enzyme主要包括三個測試:
一個是淺渲染的shallow,這個生成虛DOM對象,所以渲染最快,然而它並不能測試子組件的相關代碼。
另一個是DOM渲染mount,它會生成完整的DOM節點,所以可以測試子組件。但是要依賴一個用jsdom模擬的瀏覽器環境。
最后一個是HTML文本渲染render,它會將react組件渲染為html文本,然后在內部通過Cheerio自動生成一個Cheerio對象。

渲染方法 是否可以測試子組件 是否可以模擬交互 性能(測試500次)
shallow 116ms
mount 421ms
render 984ms

文中介紹了簡單的用法,具體的API文檔見:
Shallow Rendering
Full DOM Rendering
Static Rendered Markup


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM