问题
I'm trying to write unit tests for my node code with chai/chai-http. Everything was working fine until I switched my server to an HTTPS server, but because my certificate is signed by an internal company root and the common name of the certificate I'm using doesn't match localhost, chai is throwing an error on my request.
I'd like to do the following:
Ignore SSL errors related to domain name verification.
Set the list of CAs to check against. If this cannot be done, I'd be fine with just skipping all client-side certificate checks instead.
My code is as follows:
var chai = require('chai');
var chaiHttp = require('chai-http');
var https = require('https');
var fs = require('fs');
var server = require('../app.js');
chai.should();
chai.use(chaiHttp);
https.globalAgent.options.ca = [
fs.readFileSync('./ssl/Root.cer'),
];
describe('Attachments', function () {
it('should succeed when passed valid arguments', function (done) {
chai.request(server)
.get('/10881057300D0A4E8E8586542AA3626E41')
.set('userId', 'user')
.set('region', 'US')
.end(function (err, res) {
chai.assert(res);
res.should.have.status(200);
chai.assert(res.body);
done();
});
});
it('should return error without userId header', function (done) {
chai.request(server)
.get('/10881057300D0A4E8E8586542AA3626E41')
.end(function (err, res) {
chai.assert(res);
res.should.have.status(500);
chai.assert(res.type == 'application/json');
done();
});
});
});
And I get the following stack trace:
Uncaught AssertionError: Unspecified AssertionError
at test\test.js:21:18
at Test.Request.callback (node_modules\superagent\lib\node\index.js:615:12
)
at ClientRequest.<anonymous> (node_modules\superagent\lib\node\index.js:56
7:10)
at TLSSocket.socketErrorListener (_http_client.js:267:9)
at emitErrorNT (net.js:1253:8)
回答1:
I solved it by the suggestion here.
I think it is rejecting as invalid TLS. Even though mine was not using an invalid cert, I assume somewhere in the guts it is changing the valid cert's url to localhost or resolving to an IP address which isn't associated to the FQDN of the cert I am using. Adding the following code before the first "describe()" fixed it for me.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
Here is the full test code:
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../server');
var should = chai.should();
chai.use(chaiHttp);
// This line allows use with https
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
describe('Auth', function() {
it('should return 401 with invalid credentials', function(done){
chai.request(server)
.post('/api/v1/user/authenticate')
.send({"email":"badaccount@somedomain.com", "password": "password"})
.end(function(err, res) {
res.should.have.status(401);
done();
});
});
});
来源:https://stackoverflow.com/questions/41572681/set-accepted-ca-list-and-ignore-ssl-errors-with-chai-http