diff --git a/packages/@pollyjs/core/src/-private/response.js b/packages/@pollyjs/core/src/-private/response.js index 30f79306..034b27d3 100644 --- a/packages/@pollyjs/core/src/-private/response.js +++ b/packages/@pollyjs/core/src/-private/response.js @@ -1,4 +1,5 @@ import stringify from 'json-stable-stringify'; +import assert from '../utils/assert'; const { freeze } = Object; @@ -6,13 +7,9 @@ function formatHeader(name) { return (name || '').toLowerCase(); } -function status(statusCode) { - return parseInt(statusCode, 10) || null; -} - export default class PollyResponse { constructor(statusCode, headers, body) { - this.statusCode = status(statusCode); + this.status(statusCode || 200); this.headers = headers || {}; this.body = body; } @@ -22,7 +19,14 @@ export default class PollyResponse { } status(statusCode) { - this.statusCode = status(statusCode); + const status = parseInt(statusCode, 10); + + assert( + `[Response] Invalid status code: ${status}`, + status >= 100 && status < 600 + ); + + this.statusCode = status; return this; } diff --git a/packages/@pollyjs/core/tests/unit/-private/response-test.js b/packages/@pollyjs/core/tests/unit/-private/response-test.js index 3940b07f..c9d4453a 100644 --- a/packages/@pollyjs/core/tests/unit/-private/response-test.js +++ b/packages/@pollyjs/core/tests/unit/-private/response-test.js @@ -9,17 +9,28 @@ describe('Unit | Response', function() { expect(new PollyResponse()).to.exist; }); + it('should have a default status code of 200', function() { + expect(new PollyResponse().statusCode).to.equal(200); + }); + describe('API', function() { beforeEach(function() { response = new PollyResponse(); }); it('.status()', function() { - response.status(200); - expect(response.statusCode).to.equal(200); + [100, '404', 500, '599'].forEach(statusCode => { + expect(response.status(statusCode).statusCode).to.equal( + Number(statusCode) + ); + }); - response.status('400'); - expect(response.statusCode).to.equal(400); + [null, '', 0, 99, 600, 999].forEach(statusCode => { + expect(() => response.status(statusCode)).to.throw( + Error, + /Invalid status code/ + ); + }); }); it('.getHeader()', function() {