git地址:https://github.com/yancekang/...react
若是對你有所幫助,感謝startgit
create-react-app react-mocha-test
建立一個名稱爲 react-mocha-test
的react項目github
進入 react-mocha-test
安裝 Mocha
爲了操做的方便,請在全面環境也安裝一下Mocha
npm
npm install -g mocha
app
1.進入src
目錄,新建tool.js
文件存放咱們的須要測試的函數,函數的具體做用這裏就不須要解釋了。less
function checkSex (idcard) { if (idcard === undefined || idcard === null) { return '男' } if (parseInt(idcard.substr(16, 1)%2, 10) === 1) { return '男' } else { return '女' } } function add(x, y) { return x + y } function getParameterByName(name, url) { if (!url) url = window.location.href; /*eslint no-useless-escape: */ name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } module.exports = { checkSex, add, getParameterByName }
2.在根目錄中 test
中創建測試腳本文件,列如: index.js
函數
在文件中引入咱們要測試的函數單元測試
let {checkSex, add, getParameterByName} = require('../src/tool/tool.js')
測試
咱們還用到了chai
斷言庫,詳情請了解 chaiui
所謂"斷言",就是判斷源碼的實際執行結果與預期結果是否一致,若是不一致就拋出一個錯誤。
使用npm install chai
安裝
經過let expect = require('chai').expect
引入
接下來咱們就開始寫斷言測試,這裏只寫一種
測試第一個函數checkSex
describe('根據身份證號碼驗證用戶性別', function() { it('110101199003072615 男', function() { expect(checkSex('110101199003072615')).to.be.equal('男') }) it('110101199003072156 男', function() { expect(checkSex('110101199003072156')).to.be.equal('男') }) it('15010219900307442X 女', function() { expect(checkSex('15010219900307442X')).to.be.equal('女') }) it('150102199003075385 女', function() { expect(checkSex('150102199003075385')).to.be.equal('女') }) })
這裏舉例四種測試用例,根據身份證號碼辨別該用戶的性別和咱們預期的是否一致。
基本上,expect
斷言的寫法都是同樣的。頭部是expect
方法,尾部是斷言方法,好比equal
、a/an
、ok
、match
等。二者之間使用to
或to.be
鏈接。
若是expect
斷言不成立,就會拋出一個錯誤。事實上,只要不拋出錯誤,測試用例就算經過。
在項目根目錄執行npm test
進行單元測試,能夠看到測試結果
測試經過
測試異常