单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作
这种以测试为驱动的开发模式最大的好处就是确保一个程序模块的行为符合我们设计的测试用例。在将来修改的时候,可以极大程度地保证该模块行为仍然是正确的
如果单元测试通过,说明我们测试的这个函数能够正常工作。如果单元测试不通过,要么函数有bug,要么测试条件输入不正确,总之,需要修复使单元测试能够通过
1.试框架 mocha
mocha是JavaScript的一种单元测试框架,既可以在浏览器环境下运行,也可以在Node.js环境下运行
可以支持before、after、beforeEach和afterEach来编写初始化代码
mocha默认会执行test目录下的所有测试,不要去改变默认目录
具体的使用如下:
(1)可以全局安装 npm install mocha -g ,也可以安装在项目里面 npm install mocha --save-dev
(2)两个主要的api
describe(name, fn) 定义一组测试
it(name, fn) 定义一项测试
(a)普通测试用例
describe('#sum()', () => {
it('sum() should return 0', () => {
assert.strictEqual(sum(), 0);
});
it('sum(1) should return 1', () => {
assert.strictEqual(sum(1), 1);
});
});
(b)异步测试用例
it('#async function', async () => {
let r = await hello();
assert.strictEqual(r, 15);
});
(c)http测试用例
it('#test GET /', async () => {
let res = await request(server)
.get('/')
.expect('Content-Type', /text\/html/)
.expect(200, '<h1>Hello, world!</h1>');
});
2.断言库assert 常用API: (1)assert.ok(value[, message])
const assert = require('assert').strict;
assert.ok(true);
// OK
assert.ok(1);
// OK
assert.ok();
// AssertionError: No value argument passed to `assert.ok()`
assert.ok(false, '这是假值');
// AssertionError: 这是假值
// 在 repl 中:
assert.ok(typeof 123 === 'string');
// AssertionError: false == true
测试 value 是否为真值
如果 value 不是真值,则抛出 AssertionError,并将 message 属性设置为等于 message 参数的值。 如果未定义 message 参数,则会分配默认错误消息
(2)assert.equal(actual, expected[, message])
测试 actual 参数和 expected 参数之间的严格相等性,相当于 ==
(3)assert.strictEqual(actual, expected[, message]) 测试 actual 参数和 expected 参数之间的严格相等性,相当于 ===
(4)assert.deepEqual(actual, expected[, message])
只考虑可枚举的自身属性,“深度”相等意味着还会比较子对象的可枚举“自有”属性
(5)assert.throws(fn[, error][, message])
fn 抛出错误的函数
3.断言库should
github.com/shouldjs/sh…
var should = require('should');
var user = {
name: 'tj'
, pets: ['tobi', 'loki', 'jane', 'bandit']
};
user.should.have.property('name', 'tj');
user.should.have.property('pets').with.lengthOf(4);
// If the object was created with Object.create(null)
// then it doesn't inherit `Object.prototype`, so it will not have `.should` getter
// so you can do:
should(user).have.property('name', 'tj');
// also you can test in that way for null's
should(null).not.be.ok();
(true).should.be.ok();
10.should.be.equal(10);
(function(){ throw error; }).should.throw(Error, { a: 10 });
should跟assert对应的API:
(value).should.be.ok() 或 .should(value).be.ok()
(actual).should.equal(expected) 或 should(actual).equal(expected)
(actual).should.strictEqual(expected) 或 should(actual).strictEqual(expected)
(actual).should.deepEqual(expected) 或 should(actual).deepEqual(expected)
(fn).should.throws([message], [properties])
4.Travis CI - 持续集成服务
持续集成:提交代码有了变更,自动跑所有的构建和测试用例,返回运行结果。如果结果是正确的就会集成到主干,并且推到线上
官网:www.travis-ci.org/
参考文档:docs.travis-ci.com/user/gui-an…
www.ruanyifeng.com/blog/2017/1…
具体的使用如下:
可以用github的账号登录,然后将github上的项目添加到Travis CI里面
创建一个名为 .travis.yml 的文件,内容可以根据自己的需求进行配置.如:
出现报错:
(1)没有相应的模块
a.查看package.json里面添加相应的依赖模块,
b:全局安装模块 npm install -g mocha
(2)Cannot start chrome
before_install:
- export CHROME_BIN=chromium-browser
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
5.Travis CI node 官网:docs.travis-ci.com/user/langua…
6.学会使用Karma-前端自动化测试工具
优点:挂载多个浏览器跑测试
官网:karma-runner.github.io/latest/inde…
•全局安装 karma脚手架
npm install -g karma-cli
•安装karma相关的依赖 npm install
//前三个karma相关,后面两个测试相关
"karma": "^1.7.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"mocha": "^3.5.0",
"should": "^11.2.1"
•用karma初始化测试 karma init
使用 Git Bash 会报错,换用 windows 自带的命令行工具就 OK 了
1. Which testing framework do you want to use ? (mocha)
2. Do you want to use Require.js ? (no)
3. Do you want to capture any browsers automatically ? (Chrome)
4. What is the location of your source and test files ? (https://cdn.bootcss.com/jquery/2.2.4/jquery.js, node_modules/should/should.js, test/**.js)
5. Should any of the files included by the previous patterns be excluded ? ()
6. Do you want Karma to watch all the files and run the tests on change ? (yes)
注意:第4个问题,如果是多个文件,每个文件之后要按enter键。这些文件会以script标签的形式加载到浏览器 初始化完成之后,会在我们的项目中生成一个 karma.conf.js 文件,这个文件就是 Karma 的配置文件,内容如下:
// Karma configuration
// Generated on Thu Sep 19 2019 14:01:10 GMT+0800 (GMT+08:00)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'https://cdn.bootcss.com/jquery/2.2.4/jquery.js',
'node_modules/should/should.js',
'test/**.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
需要注意的是 karma 配置中的 singleRun 这个参数,设置为 false 的话,karma 会自动监控测试环境,默认是 Chrome, 如果你关掉了,karma 会自动重新启动一个。如果配置为 true,执行一次测试之后,karma 会自动停掉。但是放到Travis CI上面只需要执行一次就可以了
•用karma启动测试 karma start 启动之后,会自动打开浏览器。可以点击页面上的DEBUG按钮会打开一个新页面,在新页面的控制台可以看到运行结果