Chai HTTP
HTTP integration testing with Chai assertions.
Features
- integration test request composition
- test http apps or external services
- assertions for common http tasks
- chai
expect
andshould
interfaces
Installation
This is a addon plugin for the Chai Assertion Library. Install via npm.
npm install chai-http
Plugin
Use this plugin as you would all other Chai plugins.
var chai = chaiHttp = ; chai;
To use Chai HTTP on a web page, just include the dist/chai-http.js
file:
Integration Testing
Chai HTTP provides an interface for live integration testing via superagent. To do this, you must first construct a request to an application or url.
Upon construction you are provided a chainable api that allows you to specify the http VERB request (get, post, etc) that you wish to invoke.
Application / Server
You may use a function (such as an express or connect app) or a node.js http(s) server as the foundation for your request. If the server is not running, chai-http will find a suitable port to listen on for a given test.
Note: This feature is only supported on Node.js, not in web browsers.
chai
When passing an app
to request
; it will automatically open the server for
incoming requests (by calling listen()
) and, once a request has been made
the server will automatically shut down (by calling .close()
). If you want to
keep the server open, perhaps if you're making multiple requests, you must call
.keepOpen()
after .request()
, and manually close the server down:
var requester = chai Promiseall requester requester
URL
You may also use a base url as the foundation of your request.
chai
Setting up requests
Once a request is created with a given VERB (get, post, etc), you chain on these additional methods to create your request:
Method | Purpose |
---|---|
.set(key, value) |
Set request headers |
.send(data) |
Set request data (default type is JSON) |
.type(dataType) |
Change the type of the data sent from the .send() method (xml, form, etc) |
.attach(field, file, attachment) |
Attach a file |
.auth(username, password) |
Add auth headers for Basic Authentication |
.query(parmasObject) |
Chain on some GET parameters |
Examples:
.set()
// Set a request headerchai
.send()
// Send some JSONchai
.type()
// Send some Form Datachai type'form'
.attach()
// Attach a filechai
.auth()
// Authenticate with Basic authenticationchai
.query()
// Chain some GET query parameterschai // /search?name=foo&limit=10
Dealing with the response - traditional
In the following examples we use Chai's Expect assertion library:
var expect = chaiexpect;
To make the request and assert on its response, the end
method can be used:
chai ;
Caveat
Because the end
function is passed a callback, assertions are run
asynchronously. Therefore, a mechanism must be used to notify the testing
framework that the callback has completed. Otherwise, the test will pass before
the assertions are checked.
For example, in the Mocha test framework, this is
accomplished using the
done
callback, which signal that the
callback has completed, and the assertions can be verified:
; ;
When done
is passed in, Mocha will wait until the call to done()
, or until
the timeout expires. done
also accepts an
error parameter when signaling completion.
Dealing with the response - Promises
If Promise
is available, request()
becomes a Promise capable library -
and chaining of then
s becomes possible:
chai ;
Note: Node.js version 0.10.x and some older web browsers do not have native promise support. You can use any spec compliant library, such as:
- kriskowal/q
- stefanpenner/es6-promise
- petkaantonov/bluebird
- then/promise
You will need to set the library you use to
global.Promise
, before requiring in chai-http. For example:
// Add promise support if this does not exist natively.if !globalPromise globalPromise = ;var chai = ;chai;
Retaining cookies with each request
Sometimes you need to keep cookies from one request, and send them with the
next (for example, when you want to login with the first request, then access an authenticated-only resource later). For this, .request.agent()
is available:
// Log invar agent = chairequestagent ;
Note: The server started by chai.request.agent(app)
will not automatically close following the test(s). You should call agent.close()
after your tests to ensure your program exits.
Assertions
The Chai HTTP module provides a number of assertions
for the expect
and should
interfaces.
.status (code)
- @param {Number} status number
Assert that a response has a supplied status.
tohavestatus200;
.header (key[, value])
- @param {String} header key (case insensitive)
- @param {String|RegExp} header value (optional)
Assert that a Response
or Request
object has a header.
If a value is provided, equality to value will be asserted.
You may also pass a regular expression to check.
Note: When running in a web browser, the same-origin policy only allows Chai HTTP to read certain headers, which can cause assertions to fail.
tohave;tohave;tohave;
.headers
Assert that a Response
or Request
object has headers.
Note: When running in a web browser, the same-origin policy only allows Chai HTTP to read certain headers, which can cause assertions to fail.
tohaveheaders;
.ip
Assert that a string represents valid ip address.
tobeanip;tobeanip;
.json / .text / .html
Assert that a Response
or Request
object has a given content-type.
tobejson;tobehtml;tobetext;
.charset
Assert that a Response
or Request
object has a given charset.
tohavecharset'utf-8';
.redirect
Assert that a Response
object has a redirect status code.
toredirect;tonotredirect;
.redirectTo
- @param {String|RegExp} location url
Assert that a Response
object redirects to the supplied location.
to;to;
.param
- @param {String} parameter name
- @param {String} parameter value
Assert that a Request
object has a query string parameter with a given
key, (optionally) equal to value
tohave;tohave;tonothave;
.cookie
- @param {String} parameter name
- @param {String} parameter value
Assert that a Request
or Response
object has a cookie header with a
given key, (optionally) equal to value
tohavecookie'session_id';tohavecookie'session_id' '1234';tonothavecookie'PHPSESSID';tohavecookie'session_id';tohavecookie'session_id' '1234';tonothavecookie'PHPSESSID';
Releasing
chai-http
is released with semantic-release
using the plugins:
commit-analyzer
to determine the next version from commit messages.release-notes-generator
to summarize release inchangelog
to update the CHANGELOG.md file.github
to publish a GitHub release.git
to commit release assets.npm
to publish to npm.
License
(The MIT License)
Copyright (c) Jake Luer jake@alogicalparadox.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.