Extending SuperTest
Asked Answered
K

1

5

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.

Kingsize answered 18/11, 2016 at 18:27 Comment(0)
D
4

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

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

Dissidence answered 6/12, 2017 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.