基于ExpressJS令牌的应用程序的Chai断言

时间:2018-07-25 12:15:14

标签: node.js express mocha chai

我正在为基于expressjs令牌的应用编写测试,但是我阅读了chai文档并仅找到基于cookie的身份验证。解决方法是通过上面的代码通过测试,但是我需要在其他语句中使用令牌。欢迎任何提示。我正在使用mochajs进行测试。

var chai = require('chai');
var chaiHttp = require('chai-http');
var mongoose = require('mongoose');

var server = require('../app');
var Dish = require('../models/dishes');

var should = chai.should();
chai.use(chaiHttp);

describe('Users', function() {

  it('should return success on /login POST', function(done) {
    var agent = chai.request.agent(server)
    agent
      .post('/users/login')
      .send({"username": "admin", "password": "password"})
      .then(function(res) {
        res.should.have.cookie('token');
        return agent.get('/users')
          .then(function(res) {
            res.should.have.status(200);
          });
    });
    done();
  });
  
  it('should return success on /users GET', function(done) {
    chai.request(server)
    .get('/users')
    .end(function(err, res) {
      res.should.have.status(200);
      done();
    });
  });
});

describe('Dishes', function() {
  it('should list ALL dishes on /dishes GET', function(done) {
    chai.request(server)
    .get('/dishes')
    .end(function(err, res) {
      res.should.have.status(200);
      done();
    });
  });
  it('should list a SINGLE dish on /dish/<id> GET');
  it('should add a SINGLE dish on /dishes POST');
  it('should update a SINGLE dish on /dish/<id> PUT');
  it('should delete a SINGLE dish on /dish/<id> DELETE');
});

1 个答案:

答案 0 :(得分:0)

您可以在之前开始测试,然后获得令牌

let token = '';

describe('Users', () => {
    before((done) => {
        const userCredentials = {
            username: 'admin',
            password: 'password'
        };
        chai.request(server)
            .post('/api/v1/auth')
            .send(userCredentials)
            .end((err, res) => {
                console.log('res', res.body.data.customer.token);
                token = `Bearer ${res.body.data.customer.token}`;
                done();
            });
    })
    // Your test
})