我們之前討論的Jest可以說是一個零配置、高度集成的測試框架,而Mocha則相對更加靈活,你可以根據(jù)你的需求自行決定安裝哪些包來測試React。
創(chuàng)建一個新的文件夾,并初始化npm包:
npm init
然后安裝所需要的依賴包:
npm install --save-dev mocha @babel/register @babel/core @babel/preset-env @babel/preset-react
創(chuàng)建.babelrc文件:
{
"presets":["@babel/react","@babel/preset-env"]
}
安裝完成后,在package.json文件中設置測試腳本:
"scripts": {
"test": "mocha --require @babel/register test/button.spec.js"
}
這句腳本的意思:告訴npm執(zhí)行mocha測試任務,啟用編譯器標記設置讓Babel記錄器負責處理JavaScript文件。
安裝React、ReactDOM和TestUtils:
npm install --save-dev react react-dom react-test-renderer
使用Mocha編寫測試的基本依賴已經(jīng)安裝好了,但為了實現(xiàn)與Jest一樣的功能,我們還需要安裝三個包:
npm install --save-dev chai chai-spies jsdom
chai,它允許我們像Jest一樣編寫預測代碼;chai-spies,提供了spies功能,可以檢查onClick是否被調(diào)用過;jsdom,它可以創(chuàng)建獨立的DOM,這樣即使沒有真實的瀏覽器環(huán)境,也可以在控制臺中使用TestUtils。
現(xiàn)在開始編寫測試了,這里直接使用前面寫好的代碼文件button.js。直接貼代碼:
import React from 'react'
class Button extends React.Component{
render(){
return (
<button onClick={this.props.onClick}>
{this.props.text}
</button>
)
}
}
export default Button
Mocha約定,測試用例需要放在test文件夾下,所以,新建test文件夾,并創(chuàng)建button.spec.js文件。
在button.spec.js文件夾中導入所需依賴:
import React from 'react'
import TestUtils from 'react-dom/test-utils'
import ShallowRenderer from 'react-test-renderer/shallow'
import Button from '../button'
import chai, {expect} from 'chai'
import spies from 'chai-spies'
import { JSDOM } from 'jsdom'
因為Mocha是允許你自由配置的,所以我們都注意到了,導入項也就相應的多了。
所需依賴引入完畢,下一步,我們開始編輯測試用例:
const spy = chai.use(spies).spy
const {document}=(new JSDOM('')).window
global.document = document
global.window = document.defaultView
describe('Button', () => {
it('renders with text', () => {
const text = 'text'
const renderer = new ShallowRenderer()
renderer.render(<Button text={text} />)
const button = renderer.getRenderOutput()
expect(button.type).to.equal('button')
expect(button.props.children).to.equal(text)
})
it('fires the onClick callback', () => {
const onClick = spy()
const tree = TestUtils.renderIntoDocument(
<Button onClick={onClick} />
)
const button = TestUtils.findRenderedDOMComponentWithTag(
tree,
'button'
)
TestUtils.Simulate.click(button)
expect(onClick).to.be.called()
})
})
讓chai使用spy,再從chai中引用我們需要的功能,設置jsdom,定義渲染React組件所需的DOM對象?;镜脑O置完成以后接下來就是測試用例的內(nèi)容了,第一個函數(shù)describe,是負責封裝相同模塊的測試用例的;第二個函數(shù)it是寫具體的測試代碼的。這里我們沒有使用toBe方法,而是鏈式調(diào)用了chai提供的to.equal方法,不過兩者作用相同。
最后,我們來執(zhí)行一遍:
npm test

這表明我們的測試已經(jīng)通過了,現(xiàn)在可以使用Mocha測試真正的組件啦!