in Engineering

Stubby: better mocking of HTTP requests in client side tests

Today we're open sourcing Stubby, a small library for stubbing client-side AJAX requests, primarily designed for use in front end tests. Stubby lets your implementation code make real HTTP requests which are intercepted just before they hit the network. This keeps your tests fast and easier to work with.

Example

Stubbing a request is done by creating an instance of Stubby and calling stub:

var stubby = new Stubby();
stubby.stub({
  url: '/users',
}).respondWith(200, ['jack', 'iain']);

Any GET request to /users will be matched to the above stub, and ['jack', 'iain'] will be returned. It is possible to match requests against headers, the request body and query params. The Stubby README fully documents the functionality Stubby provides. The repository also includes examples of tests that use Stubby.

Why

To keep our implementation tests close to reality we wanted to avoid stubbing any application code and instead stub the requests at the network layer. Stubby uses Pretender, which replaces the native XMLHttpRequest object, meaning our request stubs don't interact at all with our application code.

JSON Schema Validation

Stubby provides an optional plugin for validating stubs against a JSON schema. When this is used, any stubs will be validated against the given schema, ensuring the URLs, parameters and request bodies stubbed are all valid. If they are not, the tests will fail. This helps us ensure our stubs are accurate and realistic, and prevents our tests falling out of date with our API. At GoCardless we've invested heavily in the JSON Schema specification for describing our API.

Getting Started

You can install Stubby with Bower:

bower install stubby

Or for further information and to report issues, you can check out Stubby on GitHub.

We're hiring developers
See job listing
By using this site you agree to the use of cookies for analytics, personalised content and ads. Learn more