diff --git a/src/test.ts b/src/test.ts index 00869e0..320d776 100644 --- a/src/test.ts +++ b/src/test.ts @@ -123,6 +123,58 @@ export class Test extends Request { return this; } + /** + * UnExpectations: + * + * .unexpectHeader('Content-Type') + * .unexpectHeader('Content-Type', fn) + */ + unexpectHeader(name: string, fn?: CallbackFunction) { + if (typeof fn === 'function') { + this.end(fn); + } + + // header + if (typeof name === 'string') { + this._asserts.push(this._unexpectHeader.bind(this, name)); + } + return this; + } + + /** + * Expectations: + * + * .expectHeader('Content-Type') + * .expectHeader('Content-Type', fn) + */ + expectHeader(name: string, fn?: CallbackFunction) { + if (typeof fn === 'function') { + this.end(fn); + } + + // header + if (typeof name === 'string') { + this._asserts.push(this._expectHeader.bind(this, name)); + } + return this; + } + + _unexpectHeader(name: string, res: Response) { + const actual = res.headers[name.toLowerCase()]; + if (actual) { + return new AssertError('unexpected "' + name + '" header field, got "' + actual + '"', + name, actual, + ); + } + } + + _expectHeader(name: string, res: Response) { + const actual = res.headers[name.toLowerCase()]; + if (!actual) { + return new AssertError('expected "' + name + '" header field', name, actual); + } + } + /** * Defer invoking superagent's `.end()` until * the server is listening. diff --git a/test/supertest.test.ts b/test/supertest.test.ts index 5570207..d7222e8 100644 --- a/test/supertest.test.ts +++ b/test/supertest.test.ts @@ -360,6 +360,67 @@ describe('request(app)', function() { }); }); + describe('.expectHeader(name, fn)', function() { + it('should expect header exists', function(done) { + const app = express(); + + app.get('/', function(_req, res) { + res.setHeader('Foo-Bar', 'ok'); + res.send('hey'); + }); + + request(app) + .get('/') + .expect(200) + .expectHeader('Foo-Bar') + .expectHeader('content-type') + .end(done); + }); + + it('should expect header exists with callback', function(done) { + const app = express(); + + app.get('/', function(_req, res) { + res.setHeader('Foo-Bar', 'ok'); + res.send('hey'); + }); + + request(app) + .get('/') + .expect(200) + .expectHeader('Foo-Bar', done); + }); + }); + + describe('.unexpectHeader(name, fn)', function() { + it('should expect header not exists', function(done) { + const app = express(); + + app.get('/', function(_req, res) { + res.send('hey'); + }); + + request(app) + .get('/') + .expect(200) + .unexpectHeader('Foo-Bar') + .end(done); + }); + + it('should expect header not exists with callback', function(done) { + const app = express(); + + app.get('/', function(_req, res) { + res.send('hey'); + }); + + request(app) + .get('/') + .expect(200) + .unexpectHeader('Foo-Bar', done); + }); + }); + describe('.expect(status[, fn])', function() { it('should assert the response status', function(done) { const app = express();