Mocha - 为什么 before() 没有完成 'before' 它,我该怎么做?

Mocha - why before() was not finished 'before' it and how can I do that?

我需要在 (post lib.js) 之前调用 API 请求并在 it[] 中检查结果=32=].

无论我在尝试什么,每次都执行it before finishing before and 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:// ....

已解决

当我将 before 更改为 async 并在 [=39= 中删除 then ] 功能,它按预期工作。

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)