Skip to content

Commit

Permalink
Allows expect to accept an array of statuses
Browse files Browse the repository at this point in the history
By accepting an array of expected values for status, expect can now assert a range of returned statuses codes. This is useful when we don't know the exact code but we expect a range: 200/204, redirects, etc. See: #389
  • Loading branch information
juanvillegas committed Apr 12, 2021
1 parent 1bb8c66 commit ab252f3
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/test.js
Expand Up @@ -101,6 +101,7 @@ function wrapAssertFn(assertFn) {
* .expect('Content-Type', 'application/json')
* .expect('Content-Type', 'application/json', fn)
* .expect(fn)
* .expect([200, 404])
*
* @return {Test}
* @api public
Expand All @@ -125,6 +126,12 @@ Test.prototype.expect = function(a, b, c) {
return this;
}

// multiple statuses
if (Array.isArray(a)) {
this._asserts.push(wrapAssertFn(this._assertStatusArray.bind(this, a)));
return this;
}

// header field
if (typeof b === 'string' || typeof b === 'number' || b instanceof RegExp) {
this._asserts.push(wrapAssertFn(this._assertHeader.bind(this, { name: '' + a, value: b })));
Expand Down Expand Up @@ -297,6 +304,25 @@ Test.prototype._assertStatus = function(status, res) {
}
};

/**
* Perform assertions on the response status and return an Error upon failure.
*
* @param {Array<Number>} statusArray
* @param {Response} res
* @return {?Error}
* @api private
*/

Test.prototype._assertStatusArray = function(statusArray, res) {
var b;
var expectedList;
if (!statusArray.includes(res.status)) {
b = http.STATUS_CODES[res.status];
expectedList = statusArray.join(', ');
return new Error('expected one of "' + expectedList + '", got ' + res.status + ' "' + b + '"');
}
};

/**
* Performs an assertion by calling a function and return an Error upon failure.
*
Expand Down
32 changes: 32 additions & 0 deletions test/supertest.js
Expand Up @@ -399,6 +399,38 @@ describe('request(app)', function () {
});
});

describe('.expect(statusArray)', function () {
it('should assert only status', function (done) {
const app = express();

app.get('/', function (req, res) {
res.send('hey');
});

request(app)
.get('/')
.expect([200, 404])
.end(done);
});

it('should reject if status is not in valid statuses array', function (done) {
const app = express();

app.get('/', function (req, res) {
res.send('hey');
});

request(app)
.get('/')
.expect([500, 404])
.end(function (err, res) {
err.message.should.equal('expected one of "500, 404", got 200 "OK"');
shouldIncludeStackWithThisFile(err);
done();
});
});
});

describe('.expect(status, body[, fn])', function () {
it('should assert the response body and status', function (done) {
const app = express();
Expand Down

0 comments on commit ab252f3

Please sign in to comment.