测试基础
使用mocha测试
概念
测试类型
- 单元测试: 以软件的单元为单位,对软件进行测试
- 避免依赖性问题,例如不存取数据库、不访问网络,而是使用工具虚拟出运行环境
- 步骤
- 准备所有的测试条件
- 调用(触发)所要测试的函数
- 验证运行结果是否正确
- 还原被修改的记录
- 集成测试: 多个部分在一起测试, 例如数据库连接模块测试
- 功能测试: 自动测试整个程序的某个功能,使用
Selenium工具自动打开浏览器测试 - 端对端测试: 全链路测试,从开始端到结束端的测试
- 确保整个系统能正常运行,各个子系统依赖关系正常,数据在子系统、模块之间传递正常
- 冒烟测试: 正式的全面测试开始之前,对主要功能进行的预测试
- 目的: 确认主要功能十分满足需要, 软件是否能运行
开发模式
- TDD(Test-Driven Development): 测试驱动开发
- 步骤
- 写一个测试
- 写出最小代码,使其能通过测试
- 优化代码
- 重复前三步
- 提供4个方法
suite()test()setup()teardown()
- 步骤
- BDD(Behavior-Driven Development): 行为驱动开发
- 概念:针对行为写测试, 不应针对代码实现细节
- 提供6个方法
describle()it()before()after()beforeEach()afterEach()
命令
mocha
- 默认会运行
test目录下第一层的脚本 --recursive会运行当前目录以及子目录的脚本
通配符
- shell通配符
mocha spec/{one,two}.js mocha test/unit/*.js mocha test/{,**/}*.{js,jsx} - node通配符
mocha 'test/**/*.@(js|jsx)'
命令行
--help,-h: 查看所有命令参数--reporter,-R: 指定测试报告格式,官方详细介绍spec: 默认格式tap: ``mochawesome: 以HTML格式报告- 生成不同格式的报告
- 生成markdown格式的报告
mocha --recursive -R markdown > spec.md - 生成html格式的报告
mocha -recursive -R doc > spec.html
- 生成markdown格式的报告
--growl,-G: 测试结果在桌面显示--watch,-w: 监视指定测试脚本,有变化会自动运行mocha--bail,-b: 指定只要有一个测试没有通过,就停止执行后面的测试用例--grep,-g: 用于搜索测试用例的名称--invert,-i: 只运行不符合条件的测试脚本, 必须与--grep配合使用mocha --grep "1 加 1" --invert
mocha.opts
- 命令行
mocha --recursive --reporter tap --growl - 配置项
mocha.opts文件--reporter tap --recursive --growl - 指定测试目录
mocha.opts文件server-tests --recursive ```
语言转换
- ES6
- 依赖包安装
npm i babel-polyfill --save npm i @babel/core @babel/preset-env -D .babelrc配置{ "presets": [ ["@babel/env", { "modules": false, "useBuiltIns": "usage", "corejs": 2, "shippedProposals": true }] ] }- 指定转换器
- ES6
npx mocha --compilers js:@babel/core/register
- ES6
- 依赖包安装
- CoffeScript
npx mocha --compilers coffee:coffee-script/register
延时测试
- 延时执行done
it('延时1000毫秒', function(done) { setTimeout(() => { done() }, 1e3) }) it('请求之后执行', function() { request .get('https://api.github.com') .end(function(err, res) { expect(res).to.be.an('object') done() }) }) - 返回一个promise
it('请求之后执行', function() { return request .get('https://api.github.com') .end(function(err, res) { expect(res).to.be.an('object') }) }) - 通过命令行
mocha -t 1000: 设置超时时间未1000毫秒mocha -s 1000: 设置测试延时1000毫秒执行
钩子函数
beforeafterbeforeEachafterEach
用例管理
only只运行某个用例
在浏览器中查看用例运行结果
- 执行命令:
mocha init test - 新建
add.jsfunction add(x, y) { return x + y; } - 把
add.js和chai.js加入index.html<script> mocha.setup('bdd'); </script> <script src="add.js"></script> <script src="http://chaijs.com/chai.js"></script> <script src="tests.js"></script> <script> mocha.run(); </script> - 新建
tests.jsvar expect = chai.expect; describe('加法函数的测试', function() { it('1 加 1 应该等于 2', function() { expect(add(1, 1)).to.be.equal(2); }); it('任何数加0等于自身', function() { expect(add(1, 0)).to.be.equal(1); expect(add(0, 0)).to.be.equal(0); }); });

浙公网安备 33010602011771号