Extend the unexpected assertion library with support for testing Express middleware
var expect = require'unexpected'cloneinstallPluginrequire'unexpected-express';var contentType = reqheaders'accept' || 'text/plain';if contentType !== 'text/plain' && contentType !== 'text/html'return next400;ressetHeader'Content-Type' contentType;var body = 'Here goes ' + requrl + ' as ' + contentType;if contentType === 'text/html'body = '<html>' + bodyreplace/&/g '&'replace/</g '<' + '</html>';ressendbody;describe'myMiddleware'it'should handle a simple request'expectrequire'express'usemyMiddleware 'to yield exchange'request:url: '/blah'headers:Accept: 'text/plain'response:statusCode: 200headers:'Content-Type': 'text/plain'body: 'Here goes /blah as text/plain'done;;;
If you're going to test a piece of middleware extensively, you can create your own custom assertion around that to increase DRYness and put the request properties into the subject's spot:
expectaddAssertion'to yield a response of'expectrequire'express'usemyMiddleware 'to yield exchange'request: subjectresponse: valuedone;;describe'myMiddleware'it'should default to text/plain'expect'/barf' 'to yield a response of' 'Here goes /barf as text/plain' done;;it'should support text/html'expecturl: '/quux' headers: Accept: 'text/html' 'to yield a response of' '<html>Here goes /quux as text/html</html>' done;;it'should entitify less than and ampersand chars in text/html'expecturl: '/<h&ey<' headers: Accept: 'text/html' 'to yield a response of' '<html>Here goes /<h&ey< as text/html</html>' done;;it'should not entitify in text/plain'expect'/<hey' 'to yield a response of' 'Here goes /<hey as text/plain' done;;it'should return a 400 if asked for an unsupported Content-Type'expecturl: '/something' headers: Accept: 'text/calendar' 'to yield a response of' statusCode: 400 errorPassedToNext: true done;;it'should return a 404 for /baz'expect'/baz' 'to yield a response of' statusCode: 404 body: 'I could not find /baz' done;;;
You'll get a nice diff when expectations aren't met:
- Normalizes header names so you don't need to use the ugly lower-case form in the assertions
- The expected response bodies can be specified as either strings, objects (implies JSON), or Buffer instances
- Request bodies can be provided as either strings, objects (implies JSON), Buffer instances, or streams.
- Request body streams that are instances of https://github.com/felixge/node-form-data are special cased to implicitly set the
Unexpected-express is licensed under a standard 3-clause BSD license
-- see the
LICENSE file for details.