0

我正在开发一个使用相互 SSL 身份验证的应用程序,我想编写自动化测试来评估功能。

我已经实现了服务器,我可以用 Postman 进行测试。这个职位运作良好。

在我的摩卡测试中,我写了这个请求:

chai.request(getServer())
    .post('/users')
    .ca(fs.readFileSync(path.join(process.cwd(), 'test', 'ca-crt.pem'), 'utf-8'))
    .cert(path.join(process.cwd(), 'test', 'client1-key.pem'), 'utf-8'))
    .key(path.join(process.cwd(), 'test', 'client1-crt'), 'utf-8'))
    .send(userToCreate)
    .end((error, response) => {
         if (error !== null) {
             reject(`User creation error : ${JSON.stringify(error)}`);
         } else if (response.status !== 201) {
             reject(`User creation failed : ${JSON.stringify(response.status)}`);
         } else {
             resolve(response.body);
         }
    });

但是此请求不会向服务器发送任何证书:

  • request.socket.authorized = 未定义

我尝试使用 HTTPS 代理:

let agent = new Agent({
    ca: fs.readFileSync(path.join(process.cwd(), 'test', 'ca-crt.pem'), 'utf-8'),
    key: fs.readFileSync(path.join(process.cwd(), 'test', 'client1-key.pem'), 'utf-8'),
    cert: fs.readFileSync(path.join(process.cwd(), 'test', 'client1-crt.pem'), 'utf-8')
});
chai.request(getServer())
    .post('/users')
    .agent(agent)
    .send(userToCreate)
    .end((error, response) => {
         if (error !== null) {
             reject(`User creation error : ${JSON.stringify(error)}`);
         } else if (response.status !== 201) {
             reject(`User creation failed : ${JSON.stringify(response.status)}`);
         } else {
             resolve(response.body);
         }
    });

但是此请求不会向服务器发送任何证书:

  • request.socket.authorized = 未定义
  • 我在 mocha 测试中遇到 ERR_INVALID_PROTOCOL 异常

有人可以帮我吗?

4

1 回答 1

0

我终于通过直接使用superagent而不是chai-http解决了这个问题。尽管 chai-http 使用了 superagent,但看起来实现缺少方法 ca、cert 和 key。所以下面的语法为我解决了这个问题:

superAgent
    .post('http:/localhost/users')
    .ca(fs.readFileSync(path.join(process.cwd(), 'test', 'ca-crt.pem'), 'utf-8'))
    .cert(fs.readFileSync(path.join(process.cwd(), 'test', 'client1-key.pem'), 'utf-8'))
    .key(fs.readFileSync(path.join(process.cwd(), 'test', 'client1-crt'), 'utf-8'))
    .send(sentBody)
    .end((error, response) => {
        if (error !== null) {
            reject(`User creation error : ${JSON.stringify(error)});
        } else if (response.status !== 201) {
            reject(`User creation failed : ${JSON.stringify(response.status)});
        } else {
            resolve(response.body);
        }
    }
});
于 2020-02-06T14:38:35.043 回答