NodeJS 使用 supertest 测试 HTTPS 服务器

use*_*306 5 javascript https certificate node.js supertest

我读到了有关supertest 的内容。我设法测试了两条路线:

it('notAuthorized', function (done) {
    request.agent(server)
        .get('/notAuthorized')
        .expect('Content-Type', /html/)
        .expect(200)
        .expect(/Not authorized!/)
        .end(done)
})

it('redirect', function (done) {
    request.agent(server)
        .get('/no-valid-route')
        .expect('Content-Type', /plain/)
        .expect(302)
        .expect('Location', '/notAuthorized')
        .expect(/Moved Temporarily/)
        .end(done)
})
Run Code Online (Sandbox Code Playgroud)


然而,当我想访问其他页面(我需要注册的页面)时,问题就出现了。我找到了这个常规注册的解决方案:

describe('When logged in', function () {
    before(function (done) {
        // login the user
        agent
            .post('/users/session')
            .field('email', 'foobar@example.com')
            .field('password', 'foobar')
            .end(done)
    })

    // ...
})
Run Code Online (Sandbox Code Playgroud)


在我的应用程序中,我使用证书进行注册。我可以用我的证书以某种方式配置测试吗?更改我的 https 选项也不起作用:

///////////////////
// https options
var options = {
    // ...
    requestCert: false,
    rejectUnauthorized: false
};
Run Code Online (Sandbox Code Playgroud)


我认为这是因为我在每条路线 中使用的中间件:

 exports.isAuthenticated = function(req, res, next){
    if(req.client.authorized) {
        // user authorized
        if(!req.session.user) {
            // set user session
            var cert = req.connection.getPeerCertificate().subject;
        // ..
Run Code Online (Sandbox Code Playgroud)


// profile
app.get("/profile", mw.isAuthenticated, profileController.getProfile);

// user
app.get("/users", mw.isAuthenticated, userController.getUsers);

// chat
app.get("/chat", mw.isAuthenticated, chatController.getChat);
Run Code Online (Sandbox Code Playgroud)


问题:

  • 无论如何,我可以使用我的证书配置代理吗?
  • 我是否应该过度考虑在每条路线中使用中间件的设计isAuthenticated
  • 我可以以某种方式更改超级测试代理的 cookie 对象吗?

如果我可以像下面的代码片段一样设置 req 对象,我可能会有一个解决方案。

    req : {
        client : {
            authorized : true
        },
        connection :{
            getPeerCertificate : function(){
                this.subject = 1;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 1

简而言之,您必须对 supertest 的 TestAgent 类、superagent 的 Agent 类以及 superagent 的 lib/node/index.js 导出的“请求”进行猴子补丁。

Superagent 仅设计用于跟踪与服务器关联的 CA,据我所知 supertest 甚至不支持这一点。底层请求实际上是在 index.js 中发出的,并且没有 API 挂钩到您需要传递的任何证书或密钥选项。