mocha单元测试
browser
mocha init test
test.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>Mocha Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="https://www.chaijs.com/chai.js"></script>
<script src="https://unpkg.com/mocha/mocha.js"></script>
<script class="mocha-init">
mocha.setup('bdd')
mocha.checkLeaks()
mocha.setup({ globals: ['uni', 'UniAppJSBridge'] }) // 设置全局变量,避免mocha与chai检测泄漏
</script>
<script>
const assert = chai.assert
const ret = {a: 1}
describe('#test', () => {
it('一个json对象', () => {
assert.isObject(ret)
})
})
</script>
<script class="mocha-exec">
mocha.checkLeaks(false) // 网页端可以考虑关闭全局检测
mocha.run() // 追加.globals(['http'])可以显式的添加全局声明
</script>
</body>
</html>
不报错就正常,所以自己写assert也不是不行。
function assert(func, result, ...params) {
let passed = func(...params) === result
if(!passed) {
throw new Error('未测试通过')
}
}
function search(val) {
return val
}
describe('#index.js', () => {
describe('测试search是否返回本身', () => {
before(function() {
console.log('before:')
})
after(function() {
console.log('after.')
})
beforeEach(function() {
console.log(' beforeEach:')
})
afterEach(function() {
console.log(' afterEach.')
})
it('search(1) should return 1', () => {
assert(search, 1, 1)
})
})
})
// 超时设置
describe('#timeout', () => {
it('function', function() {
this.timeout(5000)
})
it('array', () => {
this.timeout(5000)
}).timeout(5000)
})
nodejs
const assert = require('assert');
const sum = require('../hello');
describe('#hello.js', () => {
describe('#sum()', () => {
before(function () {
console.log('before:');
});
after(function () {
console.log('after.');
});
beforeEach(function () {
console.log(' beforeEach:');
});
afterEach(function () {
console.log(' afterEach.');
});
it('sum() should return 0', () => {
assert.strictEqual(sum(), 0);
});
it('sum(1) should return 1', () => {
assert.strictEqual(sum(1), 1);
});
it('sum(1, 2) should return 3', () => {
assert.strictEqual(sum(1, 2), 3);
});
it('sum(1, 2, 3) should return 6', () => {
assert.strictEqual(sum(1, 2, 3), 6);
});
});
})
nodejs异步
const chai = require('chai')
const expect = chai.expect
describe('index', () => {
it('测试根web页面获取', async () => {
let ret = await axios.get('/')
expect(ret).to.include('html')
})
})