chai-http:无法在断言时读取未定义的属性“标头”<匿名>

问题描述

在gitlab管道上运行单元测试时出现此错误,但是在我的本地环境下可以正常工作

TypeError: Cannot read property 'headers' of undefined
    at Assertion.<anonymous> (node_modules/chai-http/lib/http.js:175:19)
    at Assertion.propertyGetter (node_modules/chai/lib/chai/utils/addProperty.js:62:29)
    at Object.get (<anonymous>)
    at Object.proxyGetter [as get] (node_modules/chai/lib/chai/utils/proxify.js:98:22)
    at Assertion.<anonymous> (node_modules/chai-http/lib/http.js:224:40)
    at Assertion.propertyGetter (node_modules/chai/lib/chai/utils/addProperty.js:62:29)
    at Object.get (<anonymous>)
    at Object.proxyGetter [as get] (node_modules/chai/lib/chai/utils/proxify.js:98:22)
    at /app/tests/Auth/AuthGetRegister.js:10:21
    at Test.Request.callback (node_modules/superagent/lib/node/index.js:728:3)
    at ClientRequest.<anonymous> (node_modules/superagent/lib/node/index.js:647:10)
    at Socket.socketErrorListener (_http_client.js:469:9)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processticksAndRejections (internal/process/task_queues.js:80:21)

这是我的单元测试文件体系结构:

tests/
├── Auth/
│   ├── AuthGetRegister.js
├── common.js
└── top.js

该应用程序还在docker环境下运行。

单元测试通过以下命令运行:

./node_modules/.bin/mocha tests --reporter mocha-junit-reporter --reporter-options mochaFile=./test_results/test-results.xml --unhandled-rejections=strict

common.js:

let chai = require("chai");
let chaiHttp = require('chai-http');
let jwt = require('jsonwebtoken');
let fs = require('fs');

let privateKey = fs.readFileSync( __dirname + '/../RSA/jwtRS256.key');
let options = {
    server: "http://localhost:3000/api",jwt: jwt.sign({ userId: "fa76aff7-83e7-4ec2-b3e7-79d1629577b0" },privateKey,{ expiresIn: '3m',algorithm: 'RS256' })
};

chai.use(chaiHttp);

exports.options = options;
exports.chai = chai;
exports.assert = chai.assert;
exports.expect = chai.expect;

top.js:

var common = require("./common");

/*
**  Auth
*/

describe("GET /api/auth/register",function () {
    require('./Auth/AuthGetRegister');
});

AuthGetRegister.js:

let common = require("../common");
let options = common.options;
let chai = common.chai;
let expect = common.expect;

it('it should return status 200 with a list of pathologies',(done) => {
    chai.request(options.server)
        .get('/auth/register')
        .end((err,res) => {
            expect(res).to.be.json;
            expect(res).to.have.status(200);
            done();
        });
});

我将AuthGetRegister作为示例,但所有单元测试都遇到相同的错误

我已经尝试了here提出的解决方法,但这确实起作用。

解决方法

这是我的gitlab配置问题。单元测试是在服务器完全运行之前运行的。

我添加了一个wait-for-it脚本来等待服务器运行,然后运行单元测试。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...