@contexts/http
@contexts/http
is The Http(s) Testing Context For Super-Test Style Assertions.
- Includes Standard Assertions (get, set, assert) And Cookies Assertions (count, presence, value, attribute).
- Allows To Be Extended With JSDocumented Custom Assertions.
- Supports sessions to carry on cookies between requests automatically.
yarn add @contexts/http
Table Of Contents
- Table Of Contents
- API
- class HttpContext
-
Tester
assert(code: number, body: (string|RegExp|Object)=): Tester
assert(header: string, value: ?(string|RegExp)): Tester
-
assert(assertion: function(Aqt.Return)): Tester
set(header: string, value: string): Tester
post(path: string?, data: string|Object?, options: AqtOptions?): Tester
postForm(path: string?, cb: async function(Form), options: AqtOptions?): Tester
session(): Tester
- Extending
- CookiesContext
- Copyright
API
The package is available by importing its default and named classes. When extending the context, the Tester
class is required. The CookiesContext is an extension of the HttpContext that provides assertions for the returned set-cookie
header.
import HttpContext, { Tester } from '@contexts/http'
import CookiesContext, { CookiesTester } from '@contexts/http/cookie'
class HttpContext
This testing context is to be used with Zoroaster Context Testing Framework. Once it is defined as part of a test suite, it will be available to all inner tests via the arguments. It allows to specify the middleware function to start the server with, and provides an API to send requests, while setting headers, and then assert on the result that came back. It was inspired by supertest
, but is asynchronous in nature so that no done
has to be called — just the promise needs to be awaited on.
start(
fn: (req: IncomingMessage, res: ServerResponse),
secure: boolean=,
): Tester
Starts the server with the given request listener function. It will setup an upper layer over the listener to try it and catch any errors in it. If there were errors, the status code will be set to 500
and the response will be ended with the error message. If there was no error, the status code will be set by Node.JS to 200
automatically, if the request listener didn't set it. This is done so that assertion methods can be called inside of the supplied function. If the server needs to be started without the wrapper handler, the startPlain
method can be used instead.
When the secure
option is passed, the HTTPS server with self-signed keys will be started and process.env.NODE_TLS_REJECT_UNAUTHORIZED
will be set to 0
so make sure this context is only used for testing, and not on the production env.
// the handler installed by the `start` method.
const handler = async (req, res) => {
try {
await fn(req, res)
res.statusCode = 200
} catch (err) {
res.statusCode = 500
res.write(err.message)
if (this._debug) console.error(error.stack)
} finally {
res.end()
}
}
server.start(handler)
Middleware Constructor Testing Strategy |
---|
/**
* Creates a middleware for the given list of users.
* @param {Object<string, string>} users
*/
const makeMiddleware = (users) => {
/**
* Updates the request to have the user information if the token is found.
* @param {http.IncomingMessage} req
*/
const middleware = (req) => {
const token = req.headers['x-auth']
const user = users[token]
if (user) req['user'] = user
}
return middleware
}
export default makeMiddleware
/**
* @typedef {import('http').IncomingMessage} http.IncomingMessage
* @typedef {import('http').ServerResponse} http.ServerResponse
*/ |
We update the source code to export a constructor of middleware, based on the given options. In this case, the middleware will be created with the users object that is scoped within the function, rather that file, so that we can pass it at the point of creating the middleware. |
import { ok, equal } from 'assert'
import HttpContext from '@contexts/http'
import createMiddleware from '../../src/constructor'
class Context {
/**
* Creates a request listener for testing.
* @param {function(http.IncomingMessage, http.ServerResponse)} next
* Assertion method.
* @param {Object<string, string>} [users] The list of tokens-users.
*/
c(next, users = {}) {
return (req, res) => {
const mw = createMiddleware(users)
mw(req, res) // set the user on request
next(req, res)
}
}
}
/** @type {Object<string, (c: Context, h: HttpContext)} */
const TS = {
context: [Context, HttpContext],
async 'does not set the user without token'({ c }, { start }) {
await start(c((req) => {
ok(!req.user)
}))
.get('/')
.assert(200)
},
async 'does not set the user with missing token'({ c }, { start }) {
await start(c((req) => {
ok(!req.user)
}), { 'secret-token': 'User' })
.set('x-auth', 'missing-token')
.get('/')
.assert(200)
},
async 'sets the user with https'({ c }, { start }) {
await start(c((req) => {
ok(req.user)
ok(req.connection.encrypted)
}, { 'secret-token': 'User' }), true)
.set('x-auth', 'secret-token')
.get('/')
.assert(200)
},
async 'sets the correct name'({ c }, { start }) {
await start(c((req) => {
equal(req.user, 'Expected-User')
}, { 'secret-token': 'Actual-User' }))
.set('x-auth', 'secret-token')
.get('/')
.assert(200) // expecting fail
},
}
export default TS
/**
* @typedef {import('http').IncomingMessage} http.IncomingMessage
* @typedef {import('http').ServerResponse} http.ServerResponse
*/ |
The new tests require implementing a method that will call the middleware constructor prior to continuing with the request. This method is creates as part of a different context, called simply Context. It will help to create the request listener to pass to the start method, where the assertions will be written in another middleware executed after the source code one. |
|
We expected the last test to fail because in the assertion method we specified that the user name should be different from the one that was passed in the options to the middleware. Other tests pass because there were no errors in the assertion middleware. It is always required to call assert on the context instance, because simply requesting data with get will not throw anything even if the status code was not 200. |
startPlain(
fn: (req: IncomingMessage, res: ServerResponse),
secure: boolean=,
): Tester
Starts the server without wrapping the listener in the handler that would set status 200
on success and status 500
on error, and automatically finish the request. This means that the listener must manually do these things. Any uncaught error will result in run-time errors which will be caught by Zoroaster's error handling mechanism outside of the test scope, but ideally they should be dealt with by the developer. If the middleware did not end the request, the test will timeout and the connection will be destroyed by the context to close the request.
Plain Listener Testing | Wrapper Listener Testing |
---|---|
import Http from '@contexts/http'
/** @type {Object<string, (h: Http)} */
const TS = {
context: Http,
async 'sets the status code and body'(
{ startPlain }) {
await startPlain((req, res) => {
res.statusCode = 200
res.end('Hello World')
})
.get('/')
.assert(200, 'Hello World')
},
// expect to fail with global error
async 'throws an error'({ startPlain }) {
await startPlain(() => {
throw new Error('Unhandled error.')
})
.get('/')
},
// expect to timeout
async 'does not finish the request'(
{ startPlain }) {
await startPlain((req, res) => {
res.write('hello')
})
.get('/')
},
}
export default TS |
class C {
c(listener) {
return (req, res) => {
try {
listener(req, res)
} catch (err) {
res.statusCode = 500
} finally {
res.end()
}
}
}
}
/** @type {Object<string, (c:C, h: Http)} */
export const handled = {
context: [C, Http],
async 'throws an error'({ c },
{ startPlain }) {
await startPlain(c(() => {
throw new Error('Unhandled error.')
}))
.get('/')
.assert(500)
},
async 'times out'({ c }, { startPlain }) {
await startPlain(c((req, res) => {
res.write('hello')
}))
.get('/')
.assert(200, 'hello')
},
} |
With plain listener testing, the developer can test the function as if it was used on the server without any other middleware, such as error handling or automatic finishing of requests. The listener can also be wrapped in a custom service middleware that will do these admin things to support testing. | |
| |
The output shows how tests with listeners that did not handle errors fail, so did the tests with listeners that did not end the request. The handled test suite (on the right above), wraps the plain listener in a middleware that closed the connection and caught errors, setting the status code to 500 , therefore all tests passed there. The strategy is similar to the start method, but allows to implement a custom handler. |
listen(
server: http.Server|https.Server,
): Tester
Starts the given server by calling the listen
method. This method is used to test apps such as Koa
, Express
, Connect
etc, or many middleware chained together, therefore it's a higher level of testing aka integration testing that does not allow to access the response
object because no middleware is inserted into the server itself. It only allows to open URLs and assert on the results received by the request library, such as status codes, body and the headers. The server will be closed by the end of each test by the context.
Server (App) Testing | |
---|---|
import { createServer } from 'http'
import connect from 'connect'
const app = connect()
app.use((req, res, next) => {
if (req.url == '/error')
throw new Error('Uncaught error')
res.write('hello, ')
next()
})
app.use((req, res) => {
res.statusCode = 200
res.end('world!')
})
export default createServer(app) |
import H from '@contexts/http'
import server from '../../src/server'
/** @type {Object<string, (h: H)} */
const TS = {
context: H,
async 'access the server'({ listen }) {
await listen(server)
.get('/')
.assert(200, 'hello, world!')
},
async 'connect catches errors'({ listen }) {
await listen(server)
.get('/error')
.assert(500)
},
}
export default TS |
When a server needs to be tested as a whole of its middleware, the listen method of the HttpContext is used. It allows to start the server on a random port, navigate to pages served by it, and assert on the results. | |
| |
The tests will be run as usual, but if there were any errors, they will be either handled by the server library, or caught by Zoroaster as global errors. Any unended requests will result in the test timing out. |
debug(
on: boolean=,
): void
Switches on the debugging for the start
method, because it catches the error and sets the response to 500, without giving any info about the error. This will log the error that happened during assertions in the request listener. Useful to see at what point the request failed.
Debugging Errors In Start |
---|
async 'sets the code to 200'({ start, debug }) {
debug()
await start(middleware)
.get()
.assert(200)
}, |
The debug is called once before the test. When called with false , it will be switched off, but that use case is probably not going to be ever used, since it's just to debug tests. |
|
The output normally fails with the error on the status code assertions, since the handler which wraps the request listener in the start methods, catches any errors and sets the response to be of status 500 and the body to the error message. |
|
The stderr output, on the other hand, will now print the full error stack that lead to the error. |
Tester
: The instance of a Tester class is returned by the start
, startPlain
and listen
methods. It is used to chain the actions together and extends the promise that should be awaited for during the test. It provides a testing API similar to the SuperTest package, but does not require calling done
method, because the Tester class is asynchronous.
Name | Type & Description |
---|---|
constructor | new () => Tester |
Constructor method. | |
get | (path?: string) => Tester |
Send a GET request. View examples at Wiki async 'redirects to /'({ start }) {
await start(middleware)
.get()
.assert(302)
.assert('location', 'index.html')
},
async 'opens sitemap'({ start }) {
await start(middleware)
.get('/sitemap')
.assert(200)
}, |
|
options | (path?: string) => Tester |
Send a request for the async 'sends options request'({ start }) {
let method
await start((req, res) => {
method = req.method
res.setHeader('allow', 'HEAD, GET')
res.statusCode = 204
})
.options('/')
.assert(204)
.assert('allow', 'HEAD, GET')
equal(method, 'OPTIONS')
}, |
|
head | (path?: string, data?: (string | !Object), options?: !_rqt.AqtOptions) => Tester |
Send a HEAD request. View examples at Wiki async 'sends redirect for index'({ start }) {
await start(middleware)
.head()
.assert(302)
.assert('location', 'index.html')
},
async 'sends 200 for sitemap'({ start }) {
await start(middleware)
.head('/sitemap')
.assert(200)
}, |
|
put | (path?: string, data?: (string | !Object), options?: !_rqt.AqtOptions) => Tester |
Send a PUT request. |
assert(
code: number,
body: (string|RegExp|Object)=,
): Tester
Assert on the status code and body. The error message will contain the body if it was present. If the response was in JSON, it will be automatically parses by the request library, and the deep assertion will be performed.
assert(code, body=) | |
---|---|
async 'status code'({ startPlain }) {
await startPlain((_, res) => {
res.statusCode = 205
res.end()
})
.get()
.assert(205)
},
async 'status code with message'({ startPlain }) {
await startPlain((_, res) => {
res.statusCode = 205
res.end('example')
})
.get('/sitemap')
.assert(205, 'example')
},
async 'status code with regexp'({ startPlain }) {
await startPlain((_, res) => {
res.statusCode = 205
res.end('Example')
})
.get('/sitemap')
.assert(205, /example/i)
},
async 'status code with json'({ startPlain }) {
await startPlain((_, res) => {
res.statusCode = 205
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify({ hello: 'world' }))
})
.get('/sitemap')
.assert(205, { hello: 'world' })
}, |
|
assert(
header: string,
value: ?(string|RegExp),
): Tester
Assert on the response header. The value must be either a string, regular expression to match the value of the header, or null to assert that the header was not set.
assert(header, ?value) | |
---|---|
// pass
async 'header'({ startPlain }) {
await startPlain((_, res) => {
res.statusCode = 205
res.setHeader('content-type',
'application/json')
res.end('[]')
})
.get('/sitemap')
.assert(205)
.assert('content-type',
'application/json')
},
async 'header with regexp'({ startPlain }) {
await startPlain((_, res) => {
res.setHeader('content-type',
'application/json; charset=utf-8')
res.end('[]')
})
.get('/')
.assert('content-type',
/application\/json/)
},
async 'absence of a header'({ startPlain }) {
await startPlain((_, res) => {
res.end()
})
.get('/sitemap')
.assert('content-type', null)
}, |
// fail
async 'header'({ startPlain }) {
await startPlain((_, res) => {
res.statusCode = 205
res.setHeader('content-type',
'application/xml')
res.end('<pages />')
})
.get('/sitemap')
.assert(205)
.assert('content-type',
'application/json')
},
async 'header with regexp'({ startPlain }) {
await startPlain((_, res) => {
res.setHeader('content-type',
'application/json; charset=utf-8')
res.end('[]')
})
.get('/')
.assert('content-type',
/application\/xml/)
},
async 'absence of a header'({ startPlain }) {
await startPlain((_, res) => {
res.setHeader('content-type',
'text/plain')
res.end()
})
.get('/sitemap')
.assert('content-type', null)
}, |
Show Zoroaster outputexample/test/spec/assert/header.js
✓ header
✓ header with regexp
✓ absence of a header
example/test/spec/assert/header-fail.js
✗ header
| Error: Header content-type did not match value:
| - application/json
| + application/xml
| at header (example/test/spec/assert/header-fail.js:17:8)
✗ header with regexp
| Error: Header content-type did not match RexExp:
| - /application//xml/
| + application/json; charset=utf-8
| at header with regexp (example/test/spec/assert/header-fail.js:27:8)
✗ absence of a header
| Error: Header content-type was not expected:
| + text/plain
| at absence of a header (example/test/spec/assert/header-fail.js:37:8)
example/test/spec/assert/header-fail.js > header
Error: Header content-type did not match value:
- application/json
+ application/xml
at header (example/test/spec/assert/header-fail.js:17:8)
example/test/spec/assert/header-fail.js > header with regexp
Error: Header content-type did not match RexExp:
- /application//xml/
+ application/json; charset=utf-8
at header with regexp (example/test/spec/assert/header-fail.js:27:8)
example/test/spec/assert/header-fail.js > absence of a header
Error: Header content-type was not expected:
+ text/plain
at absence of a header (example/test/spec/assert/header-fail.js:37:8)
🦅 Executed 6 tests: 3 errors. |
assert(
assertion: function(Aqt.Return),
): Tester
Perform an assertion using the function that will receive the response object which is the result of the request operation with aqt
. If the tester was started with start
or startPlain
methods, it is possible to get the response object from the request listener by calling the getResponse
method on the context.
import('http').IncomingHttpHeaders
http.IncomingHttpHeaders
: The hash map of headers that are set by the server (e.g., when accessed via IncomingMessage.headers)
_rqt.AqtReturn
: The return type of the function.
Name | Type | Description |
---|---|---|
body* | !(string | Object | Buffer) | The return from the server. In case the json content-type was set by the server, the response will be parsed into an object. If binary option was used for the request, a Buffer will be returned. Otherwise, a string response is returned. |
headers* | !http.IncomingHttpHeaders | Incoming headers returned by the server. |
statusCode* | number | The status code returned by the server. |
statusMessage* | string | The status message set by the server. |
assert(assertion) | |
---|---|
async 'using a function'({ start }) {
await start((_, res) => {
res.statusCode = 205
res.setHeader('content-type', 'application/xml')
res.end()
})
.get('/sitemap')
.assert((res) => {
equal(res.headers['content-type'],
'application/xml')
})
},
async 'with response object'({ start, getResponse }) {
await start((_, res) => {
res.setHeader('content-type', 'application/xml')
res.end()
})
.get('/sitemap')
.assert(() => {
const res = getResponse()
equal(res.getHeader('content-type'),
'application/xml')
})
}, |
|
set(
header: string,
value: string,
): Tester
Sets the outgoing headers. Must be called before the get
method. It is possible to remember the result of the first request using the assert
method by storing it in a variable, and then use it for headers in the second request (see example).
set(header, value) | |
---|---|
async 'sets the header'({ startPlain }) {
await startPlain((req, res) => {
if (req.headers['x-auth'] == 'token') {
res.statusCode = 205
res.end('hello')
} else {
res.statusCode = 403
res.end('forbidden')
}
})
.set('x-auth', 'token')
.get()
.assert(205)
}, |
async 'sets a header with a function'({ start }) {
let cookie
await start((req, res) => {
res.setHeader('x-test', 'world')
res.end(req.headers['test'])
})
.set('test', 'hello')
.get('/')
.assert(200, 'hello')
.assert(({ headers: h }) => {
cookie = h['x-test']
})
.set('test', () => cookie)
.get('/')
.assert(200, 'world')
}, |
Show Zoroaster output
|
post(
path: string?,
data: string|Object?,
options: AqtOptions?,
): Tester
Posts data to the server. By default, a string will be sent with the text/plain
Content-Type, whereas an object will be encoded as the application/json
type, or it can be sent as application/x-www-form-urlencoded
data by specifying type: form
in options. To send multipart/form-data
requests, use the postForm
method.
post(path, data?, options?) | |
---|---|
async 'posts string data'({ startPlain }, { middleware }) {
await startPlain(middleware)
.post('/submit', 'hello')
.assert(200, `Received data: hello `
+ `with Content-Type text/plain`)
},
async 'posts object data'({ startPlain }, { middleware }) {
await startPlain(middleware)
.post('/submit', { test: 'ok' })
.assert(200, `Received data: {"test":"ok"} `
+ `with Content-Type application/json`)
},
async 'posts urlencoded data'({ startPlain }, { middleware }) {
await startPlain(middleware)
.post('/submit', { test: 'ok' }, {
type: 'form',
headers: {
'User-Agent': 'testing',
},
})
.assert(200, `Received data: test=ok `
+ `with Content-Type application/x-www-form-urlencoded `
+ `and User-Agent testing`)
}, |
|
Show Zoroaster output
|
postForm(
path: string?,
cb: async function(Form),
options: AqtOptions?,
): Tester
Creates a form instance, to which data and files can be appended via the supplied callback, and sends the request as multipart/form-data
to the server. See the Form interface full documentation.
postForm(path, cb, options?) | |
---|---|
async 'posts multipart/form-data'({ startPlain }, { middleware }) {
await startPlain(middleware)
.postForm('/submit', async (form) => {
form.addSection('field', 'hello-world')
await form.addFile('test/fixture/test.txt', 'file')
await form.addFile('test/fixture/test.txt', 'file', {
filename: 'testfile.txt',
})
})
.assert(200, [
[ 'field', 'hello-world', '7bit', 'text/plain' ],
[ 'file', 'test.txt', '7bit', 'application/octet-stream' ],
[ 'file', 'testfile.txt', '7bit', 'application/octet-stream' ],
])
}, |
|
Show Zoroaster output
|
session(): Tester
Turns the session mode on. In the session mode, the cookies received from the server will be stored in the internal variable, and sent along with each following request. If the server removed the cookies by setting them to an empty string, or by setting the expiry date to be in the past, they will be removed from the tester and not sent to the server.
This feature can also be switched on by setting session=true
on the context itself, so that .session()
calls are not required.
Additional cookies can be set using the .set('Cookie', {value})
method, and they will be concatenated to the cookies maintained by the session.
At the moment, only expire
property is handled, without the path
, or httpOnly
directives. This will be added in future versions.
session() | |
---|---|
import HttpContext from '../../src'
/** @type {TestSuite} */
export const viaSessionMethod = {
context: HttpContext,
async 'maintains the session'({ start, debug }) {
debug()
await start((req, res) => {
if (req.url == '/') {
res.setHeader('set-cookie', 'koa:sess=eyJtZ; path=/; httponly')
res.end('hello world')
} else if (req.url == '/exit') {
res.setHeader('set-cookie', 'koa:sess=; path=/; httponly')
res.end()
} else if (req.url == '/test') {
res.end(req.headers['cookie'])
}
})
.session()
.get('/')
.assert(200, 'hello world')
.set('Cookie', 'testing=true')
.get('/test')
.assert(200, 'koa:sess=eyJtZ;testing=true')
.get('/exit')
.get('/test')
.assert(200, 'testing=true')
},
}
/** @type {TestSuite} */
export const viaExtendingContext = {
context: class extends HttpContext {
constructor() {
super()
this.session = true
}
},
async 'maintains the session'({ start, debug }) {
debug()
await start((req, res) => {
if (req.url == '/') {
res.setHeader('set-cookie', 'koa:sess=eyJtZ; path=/; httponly')
res.end('hello world')
} else if (req.url == '/exit') {
res.setHeader('set-cookie', 'koa:sess=; path=/; httponly')
res.end()
} else if (req.url == '/test') {
res.end(req.headers['cookie'])
}
})
.get('/')
.assert(200, 'hello world')
.get('/test')
.assert(200, 'koa:sess=eyJtZ')
.get('/exit')
.get('/test')
.assert(200, '')
},
}
/** @typedef {import('../context').TestSuite} TestSuite */ |
|
Show Zoroaster output
|
Extending
The package was designed to be extended with custom assertions which are easily documented for use in tests. The only thing required is to import the Tester class, and extend it, following a few simple rules.
There are 2 parts of the @contexts/Http software: the context and the tester. The context is used to start the server, remember the response object as well as to destroy the server. The tester is what is returned by the start/startPlain/listen
methods, and is used to query the server. To implement the custom assertions with support for JSDoc, the HttpContext needs to be extended to include any private methods that could be used by the tester's assertions, but might not have to be part of the Tester API, and then implement those assertions in the tester by calling the private _addLink
method which will add the action to the promise chain, so that the await
syntax is available.
CookiesContext
The CookiesContext provides assertion methods on the set-cookie
header returned by the server. It allows to check how many times cookies were set as well as what attributes and values they had.
-
count(number)
: Assert on the number of times the cookie was set. -
name(string)
: Assert on the presence of a cookie with the given name. Same as.assert('set-cookie', /name/)
. -
value(name, value)
: Asserts on the value of the cookie. -
attribute(name, attrib)
: Asserts on the presence of an attribute in the cookie. -
attributeAndValue(name, attrib, value)
: Asserts on the value of the cookie's attribute. -
noAttribute(name, attrib)
: Asserts on the absence of an attribute in the cookie.
The context was adapted from the work in https://github.com/pillarjs/cookies. See how the tests are implemented for more info.
Examples:
-
Testing Session Middleware.
async 'sets the cookie again after a change'({ app, startApp }) { app.use((ctx) => { if (ctx.path == '/set') { ctx.session.message = 'hello' ctx.status = 204 } else { ctx.body = ctx.session.message ctx.session.money = '$$$' } }) await startApp() .get('/set').assert(204) .count(2) .get('/').assert(200, 'hello') .name('koa:sess') .count(2) },
Copyright
© Art Deco for Idio 2019 | Tech Nation Visa Sucks |
---|