Supertest: Extending Supertest

Created on 18 Nov 2016  路  1Comment  路  Source: visionmedia/supertest

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. I also tried apply it to underlying SuperAgent with no luck.

Posted it here as well:
http://stackoverflow.com/questions/40683781/extending-supertest

question

Most helpful comment

@whoisstan You should extend Test constructor.

Let me share with you a piece of my code:

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 you can use it in this way:

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

I'm using [email protected]

>All comments

@whoisstan You should extend Test constructor.

Let me share with you a piece of my code:

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 you can use it in this way:

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

I'm using [email protected]

Was this page helpful?
0 / 5 - 0 ratings