Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Persist a request (with cookies, ie sessions) Like super-agent #46

Closed
ghost opened this issue Dec 25, 2012 · 15 comments
Closed

How to Persist a request (with cookies, ie sessions) Like super-agent #46

ghost opened this issue Dec 25, 2012 · 15 comments

Comments

@ghost
Copy link

ghost commented Dec 25, 2012

To access some urls in application, one must login first. I must go back to use super-agent to unit test these urls. Can supertest do thing like this?

server = require './testServer'
request = require 'superagent'

r = request.agent()
server.start 3002

fakeUser = 
  username:'tj',
  password:'foobar'

describe 'after login', ->
      beforeEach (done)  ->
        r
          .post("http://localhost:3002/login") 
          .send(fakeUser) 
          .end (err, res) ->
            assert res.statusCode is 200
            done()

      it 'can show restricted page', (done) ->
         r
          .get("http://localhost:3002/restricted")
          .end (err, res) ->
             assert.include res.text,'Wahoo!'
             assert res.statusCode is 200
             done()
@mnmly
Copy link

mnmly commented Dec 26, 2012

@FZX As discussed in #26, it seems supertest has no support for agent yet.

Though not optimal at all, here's how I dealt with the case :[

describe "Login", ->

  # Login first
  beforeEach ( done )->

    @agent = superagent.agent()
    request( app ).post( '/login' )
      .send( { username: 'myname', password: 'secur1ty' } )
      .end ( err, res ) =>
        @agent.saveCookies( res )   # Store cookies to `@agent`
        done()


  # Now you can test :)
  describe 'GET /admin/articles', ->

    beforeEach ( done )->

      req = request( app ).get( '/admin/articles' )
      @agent.attachCookies( req )  # Attach cookies (session info) to the request
      req.end ( err, res )=>
        @res = res
        done()

    it 'should render Hello', ->

        @res.should.have.status( 200 )
        @res.text.should.include( 'Hello' )

@ghost
Copy link
Author

ghost commented Dec 26, 2012

@mnmly,thank you very much, your code is very helpful!

@jaketrent
Copy link

@mnmly Best method I've seen so far to get the niceties of both supertest and superagent. Thx.

@joaoneto
Copy link

@mnmly Login session without the agent https://gist.github.com/joaoneto/5152248

@mnmly
Copy link

mnmly commented Mar 13, 2013

@joaoneto this is much better and cleaner 👍

@vjpr
Copy link

vjpr commented Jun 6, 2013

Would be really great if this got resolved - such a common use case.

@vjpr
Copy link

vjpr commented Jun 6, 2013

Using @mnmly approach you can then monkey patch supertest and chain on the agent.

supertest = require('supertest')
supertest.Test::agent = (agent) ->
  agent.attachCookies @
  return @

request.post('/api/collections').agent(@agent).send(...).expect(200).end ...

@timmywil
Copy link

neither the agent nor cookies solution seems to work with express 3.2.6.

@timmywil
Copy link

Ah, the cookies solution works fine if I set the Cookie header instead of the cookies property.

req.set( 'Cookie', cookies )

@alekseykulikov
Copy link

thanks @timmywil, it's weird, but really works!

@gjohnson
Copy link
Contributor

@alsotang
Copy link

alsotang commented Oct 9, 2014

var supertest = require('supertest');
var app = express();

var agent = supertest.agent(app);

// then you can persist cookie

@rafaelgou
Copy link

For the records, full example for @alsotang suggest:

(this is a login form, not an API request)

var supertest = require('supertest');
var app       = require('../path_to_my/app')
var agent     = supertest.agent(app);

describe('Login', function () {
  it('should login superadmin', function(done) {
    agent
      .post('/login')
      .type('form')
      .send({ email: 'email' })
      .send({ password: 'password' })
      .expect(302)
      .expect('Location', '/')
      .expect('set-cookie', /connect.sid/)
      .end(function(err, res) {
        if (err) return done(err);
        agent.saveCookies(res);
        return done();
      });
  };
});

@theRichu
Copy link

theRichu commented Dec 26, 2016

In my case,
agent.saveCookie(res); (version 1.x)

was smoothly replaced by

agent.jar.setCookie(res.headers['set-cookie'][0]);(version 2.x)

@jinwyp
Copy link

jinwyp commented Oct 18, 2017

For the records, full example for @alsotang suggest:
You don't need do anything more with the agent.

var supertest = require('supertest');
var agent     = supertest.agent('localhost/api');

describe('Login', function () {
  it('should login superadmin', function(done) {
    agent
      .post('/login')
      .type('form')
      .send({ email: 'email' })
      .send({ password: 'password' })
      .expect(302)
      .expect('Location', '/')
      .expect('set-cookie', /connect.sid/)
      .end(function(err, res) {
        if (err) return done(err);
        // agent.saveCookies(res); don‘t need this line 
        return done();
      });
  };


it('get user info', function(done) {
// don't need do anything with cookies, agent will  attached cookies automatically based on login above
    agent
      .get('/userinfo')
      .expect(200)
      .end(function(err, res) {
        if (err) return done(err);
        return done();
      });
  };
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests