问题
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