Extending SuperTest

对着背影说爱祢 提交于 2021-01-27 13:37:31

问题


I like to use SuperTest to work with my auth system like this:

    const request = require('./valid_access_token')(require('supertest'));

    request(app)
    .get('/v1/bots')
    .valid_token()
    .expect('Content-Type', /json/)
    ...

valid_token() would insert a valid access-token

    module.exports = function (Request) {

      const Token = require('../../../app/v1/models/loader')('token');
      const UserFactory = require('../fixtures/user');

      Request.prototype.valid_token = function()
      {

        return UserFactory.createAsync('user')
        .then(function(user){
            return new Token({username: user.username}).createWeeklyAsync()
            .then(function(userToken){
                this.set("access-token",userToken[0].token);
                return this;
            })       
        })     
       }        
       return Request;
    }     

However, when I run it I get this error:

TypeError: request(...).get(...).valid_token is not a function

I tried various different approaches, no luck.


回答1:


All the credit goes to https://github.com/acabrera91

const request = require('supertest');
const Test = request.Test;

Test.prototype.authenticate = function(user) {
  const {token, xsrfToken} = user.tokens;

  return this
   .set('Authorization', `Bearer ${token}`)
   .set('X-XSRF-TOKEN', xsrfToken);
}

Then in your tests

return request(app)
  .post('/user/settings')
  .authenticate(user)
  .send(...)

https://github.com/visionmedia/supertest/issues/381#issuecomment-282198972



来源:https://stackoverflow.com/questions/40683781/extending-supertest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!