安装jesthtml
cnpm install --save-dev jest
查看版本前端
jest -V
首先要作的事情:我怎么知道要测试些什么?
若是你正在编写 Web 应用,那么一个好的起点就是测试应用的每一个页面和每一个用户交互。但 Web 应用由单元代码组成,如函数和组件,须要单独进行测试。不少时候有两种状况:node
对于这两种状况,你能够经过将测试看做检查给定函数是否产生预期结果来帮助本身。 如下是典型测试流程的样子:git
只需这样执行:输入 - 预期输出 - 断言结果github
如下是一个完整的测试用例npm
//utils.js export function fixedZero(val) { return val * 1 < 10 ? `0${val}` : val; }
//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,咱们能够看到命令台的返回浏览器
当咱们对一些比较庞大的项目,要进行成百上千个函数进行单元测试时,测试结果仅仅显示在控制台明显不够看。如何优雅的让测试结果展现出来,并能够详细的观察测试结果的具体问题呢?服务器
咱们会想到将jest的测试结果 --> 存储 --> 发请求(简单服务器) --> 发送到浏览器 --> 展现框架
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模块,这个函数的第一个参数会接收测试结果,且必须在最终返回测试结果。能够用与于接收测试结果,且在最终返回测试结果函数
首先咱们安装它: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-html-reporter的配置:
//jest.config.js module.exports={ ... testResultsProcessor:'./testReport', reporters: [ 'default', [ './node_modules/jest-html-reporter', { //输出页面标题 pageTitle: 'Test Report', //插件将会输出的HTML报告的路径。 outputPath:'testReport/JesttestReport.html', //为每一个失败的测试输出详细的失败消息。 includeFailureMsg: true, }, ], ], }
再次在命令行输入npm test utils.test.js,咱们能够看到测试结果被成功返回在testReport/JesttestReport.html中
咱们打开这个html文件,测试结果的可视化就完成啦。