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'return 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';;;
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'return expectrequire'express'usemyMiddleware 'to yield exchange'request: subjectresponse: value;;describe'myMiddleware'it'should default to text/plain'return expect'/barf' 'to yield a response of' 'Here goes /barf as text/plain';;it'should support text/html'return expecturl: '/quux' headers: Accept: 'text/html' 'to yield a response of' '<html>Here goes /quux as text/html</html>';;it'should entitify less than and ampersand chars in text/html'return expecturl: '/<h&ey<' headers: Accept: 'text/html' 'to yield a response of' '<html>Here goes /<h&ey< as text/html</html>';;it'should not entitify in text/plain'return expect'/<hey' 'to yield a response of' 'Here goes /<hey as text/plain';;it'should return a 400 if asked for an unsupported Content-Type'return expecturl: '/something' headers: Accept: 'text/calendar' 'to yield a response of' statusCode: 400 errorPassedToNext: true;;it'should return a 404 for /baz'return expect'/baz' 'to yield a response of' statusCode: 404 body: 'I could not find /baz';;;
You'll get a nice diff when expectations aren't met:
Unexpected-express is licensed under a standard 3-clause BSD license
-- see the
LICENSE file for details.