HTTP assertions made easy for theon based API clients. Inspired by supertest.
The motivation with this module is to provide a high-level abstraction for testing
HTTP layers, while still allowing you to drop down to the lower-level API provided by theon
.
- Easy to use from any theon based API client
- Dead simple declarative API
- HTTP status code expectation
- HTTP headers expections
- RegExp based matching for body and headers
- Response bodies comparison supporting deep assertions
- Custom function expectations
npm install theon-expect --save-dev
Once installed it can now be referenced by simply calling: require('theon-expect')(require('theon'))
const expect = require('theon-expect')
const theon = expect(require('theon'))
// Declare your API
const api = theon('http://api.server.com')
.collection('users')
.basePath('/users')
.set('Version', '1.0')
.resource('getById')
.path('/:id')
.render()
// Consume your API
api.users
.getById()
.param('id', '1234')
.expect(200)
.expect('Content-Type', /json/i)
.expect({ id: 1234, username: 'foo' })
.expect(res => {
if (res.status > 300) {
throw new Error('invalid status code')
}
})
.end((err, res) => {
if (err) {
return console.error('Expect error:', err)
}
})
You may use any theon methods.
Assert response status
code.
Assert response status
code and body
.
Assert response body
text with a string, regular expression, or
parsed body object.
Assert header field
value
with a string or regular expression.
Pass a custom assertion function. It'll be given the response object to check. If the response is ok, it should return falsy, most commonly by not returning anything. If the check fails, throw an error or return a truthy value like a string that'll be turned into an error.
Here the string or error throwing options are both demonstrated:
myApi.users
.getById('/')
.expect(hasPreviousAndNextKeys)
.end(done)
function hasPreviousAndNextKeys (res) {
if (!('next' in res.body)) return "missing next key"
if (!('prev' in res.body)) throw new Error("missing prev key")
}
Perform the request and invoke fn(err, res)
.
MIT