使用 Mocha 和 Node.js自带的assert做单元测试,使用SuperTest做请求接口。
Mocha 简介
mocha 提供 TDD(测试驱动开发)、BDD (行为驱动开发) 和 exports 风格的接口。
BDD是“行为驱动的开发”(Behavior-Driven Development)的简称。BDD认为,不应该针对代码的实现细节写测试,而是要针对行为写测试。BDD测试的是行为,即软件应该怎样运行。
BDD接口提供以下方法:
describe():测试套件
it():测试用例
before():所有测试用例的统一前置动作
after():所有测试用例的统一后置动作
beforeEach():每个测试用例的前置动作
afterEach():每个测试用例的后置动作
BDD的特征就是使用describe()和it() 这两个方法。before()、after()、beforeEach()和afterEach() 是为测试做辅助的作用域,它们合起来组成了hook的概念。
describe()和it()
describe()
describe()方法接收两个参数:第一个参数是一个字符串,表示测试套件的名字或标题,表示将要测试什么。第二个参数是一个函数,用来实现这个测试套件。
上面引出了一个概念:测试套件。那什么是测试套件呢?
测试套件(test suite)指的是,一组针对软件规格的某个方面的测试用例。也可以看作,对软件的某个方面的描述(describe)。结构如下:
describe("A suite", function() {
// ...
});
it()
要想理解it(),首先我们要知道什么是测试用例? 测试用例(test case)指的是,针对软件一个功能点的测试,是软件测试的最基本单位。一组相关的测试用例,构成一个测试套件。
测试用例由it函数构成,它与describe函数一样,接受两个参数:第一个参数是字符串,表示测试用例的标题;第二个参数是函数,用来实现这个测试用例。
BDD风格用例
//模块依赖
var assert = require("assert");
describe('Array', function(){ //测试套件
describe('#indexOf()', function(){
it('当值不存在时应该返回 -1', function(){ //测试用例
assert.equal(-1, [1,2,3].indexOf(5)); //断言条件
assert.equal(-1, [1,2,3].indexOf(0));
});
});
});
使用 SuperTest 测试接口
npm i --save-dev supertest
代码:
var assert = require("assert");
var request = require('supertest');
describe('测试相关接口', async function () {
const http = require('http');
const app = require('../app');
const PORT = process.env.PORT || 3000;
const SERVER = http.createServer(app.callback());
SERVER.listen(PORT, '0.0.0.0', () => {
console.log(`Running on port: http://127.0.0.1:${PORT}`);
});
before(function () {
console.log("before 函数");
});
it('接口版本', async () => {
let res = request(SERVER)
.get('/v1')
.expect('Content-Type', /application\/json/)
.expect(200)
.end(function (err, res) {
if (err) throw err;
if (res.body.name != "koa-restful-api-seed") throw Error("sssss");
});
});
it('登录接口', (done) => {
let res = request(SERVER)
.post('/v1/auth/login')
.send({
"mobile": "13688880565",
"password": "123123"
})
.expect('Content-Type', /application\/json/)
.expect(200)
.end(function (err, response) {
if (err) throw err;
assert(response.body.token1, "token 没有获取到");
return done(err)
});
});
it('测试sum', () => {
assert.strictEqual(123, 123);
});
})
引用一个地址的例子:
request = request('http://localhost:5555');
request.get('/').expect(200, function(err){
console.log(err);
});
request.get('/').expect('heya', function(err){
console.log(err);
});
参考:
https://www.npmjs.com/package/supertest
https://www.cnblogs.com/leo-yu/p/10950376.html
http://nodejs.cn/api/assert.html
https://mochajs.org/#getting-started
https://github.com/visionmedia/supertest
https://www.liaoxuefeng.com/wiki/1022910821149312/1101756368943712
修改时间 2022-02-21