chaijs / chai-http

HTTP Response assertions for the Chai Assertion Library.
http://chaijs.com/plugins/chai-http
634 stars 113 forks source link

Recommended way to extend the request class? #280

Open jayceekay opened 3 years ago

jayceekay commented 3 years ago

I was hoping to make a helper method for assisting with auth, eg. chai.request(app).get('/users').withAuth() which would ensure:

i've been putzing around trying to wrap chaiHttp just so i can wrap lib/request, then set that wrapper as chai.request rather than lib/request, but to no avail (i can't keep the 'this' context). is there a template i could borrow, or could someone point me in the right direction?

this is one approach i've tried:

import util from 'util';
import chaiHttp from 'chai-http';
import chaiRequest from 'chai-http/lib/request';

export default function MyWrapper(chai, _) {
  chaiHttp.call(this, chai, _);

  function MyRequestWrapper() {
    const args = Array.prototype.slice.call(arguments);
    return chaiRequest.apply(this, args);
  }

  util.inherits(MyRequestWrapper, chaiRequest);

  MyRequestWrapper.prototype.withAuth = () => { // optionally pass in account to authenticate
    // not working
    // this.set('authorization', `bearer ${someUser.token}`);
  };

  chai.request = MyRequestWrapper;
};

i've also tried this in the constructor:

let obj = chaiRequest.apply(this, args);
obj.withAuth = () => {}; // etc...
return obj;

but no go.