如何在 Mocha 测试用例中发送标题(“授权”、“承载令牌”)

Lee*_*thi 3 javascript unit-testing mocha.js node.js chai

我正在编写一个测试用例来测试我的 API。当我尝试测试任何开放 API 时,它运行良好。但是当我尝试将授权令牌与我的 API 一起发送时,它不起作用。这是代码:

我发送标头的方式是:

.set("Authorization", "Bearer " + token)

这是正确的发送方式吗?

我试图在 Auth 中发送授权令牌。但不能得到相同的。但是当我尝试在 Postman 中使用相同的内容时,它运行良好。

    it("Get some random Info", function(done) {
        chai
          .request(baseUrl)
          .get("/someRandomApi")
          .set("Authorization", "Bearer " + token)
          .end(function(err, res) {
            expect(res).to.have.status(200);
            done();
          });
      });
Run Code Online (Sandbox Code Playgroud)

小智 8

我喜欢按以下方式设置我的测试:

let baseUrl = 'http://localhost:9090'
let token = 'some_authorization_token'
Run Code Online (Sandbox Code Playgroud)

首先,我会实例化我的变量,baseUrltoken在测试的最顶端,紧接着use()部分。

接下来是测试的设置。

    it("Get some random Info", function(done) {
       chai.request(baseUrl)
         .get('/someRandomApi')
         .set({ "Authorization": `Bearer ${token}` })
         .then((res) => {
            expect(res).to.have.status(200)
            const body = res.body
            // console.log(body) - not really needed, but I include them as a comment
           done();
         }).catch((err) => done(err))
    });
Run Code Online (Sandbox Code Playgroud)

现在,.set()不一定必须像我的一样,也适用于您的情况。

  • 只有这个对我有用! (2认同)