chai“获取”请求返回401

时间:2019-06-06 12:02:10

标签: javascript http authorization chai http-status-code-401

我正在尝试进行一些单元测试,但是我不能,因为我得到的不是状态200,而是401

  

未捕获的AssertionError:预期{对象(_events,_eventsCount,   ...)}的状态码为200,但得到401         +预期-实际

  -401

  +200
let chai = require('chai');
let expect = chai.expect;
let chaiHttp = require('chai-http');
let summaryRoute = '/home';
let baseURL = 'https://xxx.xxx.xxx.xxx';
chai.use(chaiHttp);
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

describe('/GET /home', () => {
    it('should return a json', done => {
        chai.request(baseURL)
            .get(summaryRoute)
            .end((err, res) => {
                expect(err).to.be.null;
                expect(res).to.have.status(200);
                done();
            });
    });
});

我可以先进行登录吗,还是可以在process.env中保存用户名和密码?

我也尝试过:

const request = require('supertest');
const expect = require('expect');
let chai = require('chai');
let chaiHttp = require('chai-http');
let summaryRoute = '/home';
let baseURL = 'https://xxx.xxx.xxx.xxx';
chai.use(chaiHttp);
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

function createLoginToken(server, loginDetails, done) {
    request(server)
        .post('login')
        .send(loginDetails)
        .end(function(error, response) {
            if (error) {
                throw error;
            }
            let loginToken = "xxxxx"
            done(loginToken);
        });
}

describe('/GET /home', () => {
    it('should return a json', (done) => {
        createLoginToken(baseURL, { username: "username", password: 'password'}, function(header) {
            request(baseURL)
                .get(summaryRoute)
                .set('Authorization', 'Bearer  ' + header)
                .expect(200)
                .end(done);
        });
    });
});

但我也得到

  

错误:预期为200“确定”,得到401“未授权”

我想念什么?感谢您的时间! (在邮递员中,这可以工作,我可以得到200)

0 个答案:

没有答案