收录了这篇文章
var assert = require("assert"); var request = require('supertest'); // describe('接口测试', async function () { const http = require('http'); const app = require('../../app'); const PORT = process.env.PORT || 3003; const SERVER = http.createServer(app.callback()); it('获取 API 版本信息', (done) => { let res = request(SERVER) .get('/v1') .expect('Content-Type', /application\/json/) .expect(200) .end(function (err, response) { if (err) throw err; // if (response.body.name != "Boar") throw Error("获取版本信息失败"); assert.equal(response.body.name, "Boar"); done(); }); }); it('登录成功', (done) => { let res = request(SERVER) .post('/v1/auth/login') .send({ "mobile": "13366660012", "password": "123456" }) .expect('Content-Type', /application\/json/) .expect(200) .end(function (err, response) { if (err) throw err; assert(response.body.token, "token 没有获取到"); done() }); }); it('登录接口,用户名或密码错误', (done) => { let res = request(SERVER) .post('/v1/auth/login') .send({ "mobile": "13366660012", "password": "123456-error" }) .expect('Content-Type', /application\/json/) .expect(400) .end(function (err, response) { if (err) throw err; assert.ok(response.body.error, "没有获取到错误信息"); done() }); }); SERVER.close();
也可以直接请求API地址:
var config = { host: 'http://local.restfulapi.cn:8081' }; var assert = require("assert"); var request = require('supertest')(config.host); it('获取 API 版本信息', (done) => { request .get('/wp-json/verytheme/v1/options') .expect('Content-Type', /application\/json/) .expect(200) .end(function (err, response) { if (err) throw err; // console.log("response: ", response.body, response.statusCode) // if (response.body.name != "Boar") throw Error("获取版本信息失败"); assert.equal(response.body.name, "koa restful api"); done(); }); });
Node.js 未来的单元测试:
https://javascript.net.cn/articles/874
修改时间 2022-04-28
声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。