Drahcir
Drahcir

Reputation: 11972

Mocha async tests, reuse the same request

I'm testing an HTTP server. I was hoping I could pass done to describe(), instead of just to it(), something like this:

var request = require('supertest');

describe('Item', function(done){
    request(app).get('/').end(function(req, res){
        it('should have one thing', function(){
            // Assert on res.body
        });

        it('should have another thing', function(){
            // Assert on res.body
        });

        it('should have more things', function(){
            // Assert on res.body
        });

        done();
    });
});

This won't work, mocha never runs the tests.

The following code does work, but each time making a new HTTP request, I would prefer to use the same one.

describe('Item', function(){
    it('should have one thing', function(done){
        request(app).get('/').end(function(req, res){
            // Assert on res.body
            done();
        }
    });

    it('should have another thing', function(done){
        request(app).get('/').end(function(req, res){
            // Assert on res.body
            done();
        }
    });

    it('should more things', function(done){
        request(app).get('/').end(function(req, res){
            // Assert on res.body
            done();
        }
    });
});

How can I run the tests against the same response?

Upvotes: 1

Views: 300

Answers (1)

Golo Roden
Golo Roden

Reputation: 150624

If you test the exact same request - then why are the asserts distributed across multiple tests? IMHO there are two options:

  • Either they really belong together, then move everything into one single test, and your problem is gone.
  • Or they do not belong together, then do not work on a single request, but on individual ones to avoid side-effects. Anyway, your problem will be gone, too.

The way you're doing it currently you may have inter-dependencies between your tests, and this is - IMHO - very bad test style.

Just my 2 cents.

Upvotes: 2

Related Questions