我需要先调用API请求(发布 lib.js),然后在 it 中检查结果。
无论我每次尝试执行的操作是什么,都先完成它,然后再完成 before 和 res 变量为空,如您在输出的开始-右下方带有井号的毫秒。
test.js
const lib = require('../lib/lib.js');
global.serverurl = process.env.SERVERURL;
describe('Template Scenario', function () {
global.loginData = require('../data/template.json');
describe('Login user', function () {
var res;
before(function () {
res = lib.post('/rest/security/login/', {username: loginData.username, password: loginData.password});
});
it('should return right status code', function () {
console.log('###########################'+Date.now());
console.log(JSON.stringify(res));
res.should.have.status(200);
});
lib.js
const chai = require('chai');
chai.use(require('chai-http'));
exports.post = function (api_endpoint, request_body) {
return chai.request(serverurl)
.post(encodeURI(api_endpoint))
.send(request_body)
.then(function (r) {
console.log('***************************'+Date.now());
console.log(JSON.stringify(r));
});
}
输出
Template Scenario
Login user
###########################1571734950189
{}
1) should return right status code
0 passing (59ms)
0 pending
1 failing
1) Template Scenario
Login user
should return right status code:
AssertionError: expected {} to have keys 'status', or 'statusCode'
***************************1571734950409
{"req":{"method":"post","url":"https:// ....
答案 0 :(得分:0)
已解决
当我将之前更改为异步,并在发布功能中删除了然后时,它可以正常工作。
test.js
const chai = require('chai');
const should = chai.should();
const lib = require('../lib/lib.js');
global.serverurl = process.env.SERVERURL;
var res;
describe('Template Scenario', function () {
global.loginData = require('../data/template.json');
describe('Login user', function () {
before(async function () {
res = await lib.post('/rest/security/login/', {username: loginData.username, password: loginData.password});
});
it('should return right status code', function () {
res.should.have.status(200);
});
lib.js
const chai = require('chai');
chai.use(require('chai-http'));
exports.post = async function (api_endpoint, request_body) {
return chai.request(serverurl)
.post(encodeURI(api_endpoint))
.send(request_body);
}
输出
Template Scenario
Login user
✓ should return right status code
✓ should return correct Json schema
2 passing (97ms)