Testing requests that redirect with mocha/supertest in node

元气小坏坏 提交于 2019-12-02 17:55:33

For anyone who comes across this page, the answer to this question is pretty simple. The Moved Temporarily. response body is what is returned from supertest. See the issue for more details.

To summarize, I ended up doing something like this.

should  = require('should')
request = require('supertest')
app     = require('../../app')

describe 'authentication', ->
  describe 'POST /sessions', ->
    describe 'success', ->
      it 'redirects to the right path', (done) ->
        request(app)
          .post('/sessions')
          .send(user: 'username', password: 'password')
          .end (err, res) ->
            res.header['location'].should.include('/home')
            done()

Just check that the response header location is what you expect it to be. Testing for flash messages and view specific integration tests should be done using another method.

There is built-in assertion for this in supertest:

should  = require('should')
request = require('supertest')
app     = require('../../app')

describe 'authentication', ->
  describe 'POST /sessions', ->
    describe 'success', ->
      it 'redirects to the right path', (done) ->
        request(app)
          .post('/sessions')
          .send(user: 'username', password: 'password')
          .expect(302)
          .expect('Location', '/home')
          .end(done)

I was trying to write some integration tests for requests that redirected as well, and found a good example by the author of the module himself here.

In TJ's example, he's using chaining, so I used something like that as well.

Consider a scenario in which a logged-in user is redirected to the home page when he or she logs out.

it('should log the user out', function (done) {
  request(app)
    .get('/logout')
    .end(function (err, res) {
      if (err) return done(err);
      // Logging out should have redirected you...
      request(app)
        .get('/')
        .end(function (err, res) {
          if (err) return done(err);
          res.text.should.not.include('Testing Tester');
          res.text.should.include('login');
          done();
        });
    });
});

Depending on how many redirects you have, you might have to nest a few callbacks, but TJ's example should suffice.

describe 'authentication', ->
  describe 'POST /sessions', ->
    describe 'success', (done) ->
      it 'displays a flash', (done) ->
        request(app)
          .post('/sessions')
          .type('form')
          .field('user', 'username')
          .field('password', 'password')
          .redirects(1)
          .end (err, res) ->
            res.text.should.include('logged in')
            done()

The redirects() will follow the redirect so you can do your usual view tests.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!