Jest初識——函數單元測試自動報告
- 在開發React應用或者其他Web應用時,我們經常要進行函數單元測試,來確保函數的功能準確性
- jest是facebook開發的單元測試框架,但是他的測試結果通常是在終端或者cmd裏面顯示.
- 其形式不夠美觀,而且無法一目瞭然的看到測試結果。
準備工作
- 確保你的項目已經安裝了版本較新的jest測試框架(隨版本更迭有可能產生無法預知的BUG,如:配置屬性名變更)
- 安裝jest:cnpm install --save-dev jest
- 已完成對jest配置文件jest.config.js的基本配置
參數配置
- 根據jest官方文檔在jest.config.js中有testResultsProcessor屬性:
Property | Description | Type | Default |
---|---|---|---|
testResultsProcessor | This option allows the use of a custom results processor. This processor must be a node module that exports a function expecting an object with the following structure as the first argument and return it: | string | undefined |
這個屬性可以允許結果處理程序使用。這個處理器必須是一個輸出函數的node模塊,這個函數的第一個參數會接收測試結果,且必須在最終返回測試結果。可以用與於接收測試結果,且在最終返回測試結果
實現在瀏覽器上實現測試結果的顯示
方法
- 1.我們可以通過nodejs實現但是需要配置一個簡單的node服務器,來實現在瀏覽器顯示。但是方法過於繁瑣,不在贅述。
- 2.我們藉助於報告工具jest-html-report(本質與第一個方法沒有區別,只是這個工具是打包好的,可以直接使用)
首先我們安裝它:cnpm install jest-html-report --save-dev
在jest.config.js中,具體配置jest-html-reporter的屬性
用到的屬性:
Property | Description | Type | Default |
---|---|---|---|
pageTitle | The title of the document | string | "Test Suite" |
outputPath | The path to where the plugin will output the HTML report | string | "./test-report.html" |
includeFailureMsg | If this setting is set to true, this will output the detailed failure message for each failed test. | boolean | false |
其他屬性參考官方文檔:https://github.com/Hargne/jes...
jest.config.js配置:
//jest.config.js
module.exports={
...
testResultsProcessor:'./testReport',
reporters: [
'default',
[
'./node_modules/jest-html-reporter',
{
pageTitle: 'Test Report',
outputPath: 'testReport/JesttestReport.html',
includeFailureMsg: true,
},
],
],
}
實現單元測試
測試用例
以下是一個完整的測試用例
- 創建js文件,描述測試函數
//utils.js
export function fixedZero(val) {
return val * 1 < 10 ? `0${val}` : val;
}
- 創建.test.js文件,添加斷言
//utils.test.js
import { fixedZero } from './utils';
...
// describe('函數分組測試描述',() => {
// test('測試描述', () => {
// expect("").toBe("");
// });
// })
describe('fixedZero tests', () => {
it('should not pad large numbers', () => {
expect(fixedZero(10)).toEqual(10);
expect(fixedZero(11)).toEqual(11);
expect(fixedZero(15)).toEqual(15);
expect(fixedZero(20)).toEqual(20);
expect(fixedZero(100)).toEqual(100);
expect(fixedZero(1000)).toEqual(1000);
expect(fixedZero(1000)).toEqual(1000);
});
it('should pad single digit numbers and return them as string', () => {
expect(fixedZero(0)).toEqual('00');
expect(fixedZero(1)).toEqual('01');
expect(fixedZero(2)).toEqual('02');
expect(fixedZero(3)).toEqual('03');
expect(fixedZero(4)).toEqual('04');
expect(fixedZero(5)).toEqual('05');
expect(fixedZero(6)).toEqual('06');
expect(fixedZero(7)).toEqual('07');
expect(fixedZero(8)).toEqual('08');
expect(fixedZero(9)).toEqual('09');
});
});
在命令行輸入npm test utils.test.js,我們可以看到命令臺的返回
測試結果被成功返回在testReport/JesttestReport.html我們打開這個html文件
總結
- 優點:實現了前端單元測試自動化生成報告
- 缺點:每次重新測試無法刷新測試結果,必須手動重新打開結果html網頁
文檔
- jest官方文檔:https://jestjs.io/docs/en/get...
- jest-html-reporter官方文檔:https://github.com/Hargne/jes...