3

This is more or less a duplicate of supertest test express middleware

but after a year, I figured I'd start a new question.

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

var app1 = express();    
app1.get('/myapp', function (req, res) {
  res.send(200, { name: 'myapp' });
});

request = request(app1);
it('should fail', function () {
  request
  .get('/hahahahahahahaha')
  .expect(123);
});

As far as I can tell, that will always erroneously pass. The fact that the path is wrong and is expecting a different status code doesn't matter.

And - more generically (without Express), it looks like this always passes, also:

it('should fail', function () {
    request('http://thisdoesnotexist.mydomain')
        .get()
        .expect(200);
});

This doesn't work either:

it('should fail', function () {
    request('http://thisdoesnotexist.mydomain')
        .get()
        .expect(200)
        .end(function (err, res) {
            if (err) {
                throw err;
            }
    });
});

Any thought as to why this happens, or how to actually test such a scenario?

Community
  • 1
  • 1
Mike
  • 643
  • 3
  • 10

2 Answers2

7

With supertest you need to terminate your chain somehow.

expect will take a finished callback as the second parameter, and you can use the build in mocha callback for this. Like so:

describe('potato', function() {
    it('should fail', function(done) {
        request
            .get('/hahahahahahahaha')
            .expect(123, done);
    });
});

Specifying a done option like this will instruct mocha to wait until it's heard back from you before proceeding to the next test.

Andrew Lavers
  • 8,023
  • 1
  • 33
  • 50
  • I am not passing a callback because I need the tests to execute synchronously. I tried the second option, but the callback passed to end in the second option is never hit, and thus the error is never thrown. – Mike May 21 '15 at 22:13
  • 2
    If by "synchronously" you mean you need test A to finish before test B runs, then specifying a `done` callback as the second parameter to `it` will achieve this for you. I've simplified my answer a bit. – Andrew Lavers May 21 '15 at 22:23
0

The difference is the parameter: done

describe('XXX', function() {
  it('XXX', function() {
    // always passing
  })
})

describe('YYY', function(done) {
  it('YYY', function() {
    // always passing
  })
})

describe('ZZZ', function() {
  it('ZZZ', function(done) {
    // normal
  })
})
kenberkeley
  • 8,449
  • 3
  • 35
  • 25