问题描述
在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作为示例,但所有单元测试都遇到相同的错误。
解决方法
这是我的gitlab配置问题。单元测试是在服务器完全运行之前运行的。
我添加了一个wait-for-it脚本来等待服务器运行,然后运行单元测试。