spec-mate is a powerful API testing framework developed by S25Digital, designed to help developers streamline the process of testing and validating APIs. With support for advanced assertions, customizable hooks, and seamless integration with tools like Nock, spec-mate makes it easy to test even the most complex APIs.
- Features
- Installation
- Usage
- Comprehensive Assertions
- Advanced Features
- Test Example with Nock
- Hooks
- Contribution
- About S25Digital
- License
- Comprehensive API Testing: Test all aspects of an API response, from headers and status codes to cookies and JSON bodies.
- Built-in Assertions: Easily validate JSON paths, headers, status codes, cookies, and more.
- Custom Assertions: Extend functionality by adding user-defined assertions.
- Mocking Support: Easily integrate with Nock to mock HTTP requests and responses.
- Integration with Chai: Works seamlessly with Chai assertions, including
chai-json-schema
. - Hooks for Custom Logic: Allows you to add pre- and post-request logic via hooks.
To install spec-mate, use npm or yarn:
npm install spec-mate
Additionally, you’ll need some supporting libraries for testing:
npm install chai axios nock --save-dev
import { SpecMate } from 'spec-mate';
const api = new SpecMate('https://api.example.com');
async function runTest() {
await api.request('/users')
.withMethod('GET')
.expectStatus(200)
.expectHeader('Content-Type', 'application/json')
.expectJsonPath('results[0].name', 'John Doe')
.run();
}
runTest();
This example demonstrates a simple GET
request with validations for the response status code, content type, and a specific JSON path.
SpecMate offers a range of built-in assertions to validate various aspects of an API response. Below is a detailed list of available assertions with usage examples.
Ensure that the response has the expected status code.
.expectStatus(200)
Check if a specific header exists and has the expected value.
.expectHeader('Content-Type', 'application/json')
Ensure a specific header is present in the response.
.expectHeaderExists('Content-Type')
Ensure a specific header is absent in the response.
.expectHeaderNotExists('X-Powered-By')
Validate that a value exists at a specific path within the JSON response body.
.expectJsonPath('results[0].name', 'John Doe')
Check the length of an array or object at a specific JSON path.
.expectJsonLength('results', 3)
Ensure the response body contains a specific text.
.expectBodyContains('user')
Ensure that the response body matches a regular expression.
.expectBodyMatches(/"name": "John Doe"/)
Verify that the Content-Type
header matches a specific type.
.expectContentType('application/json')
Ensure that the status code falls within a specific range.
.expectStatusInRange(200, 299)
Check if the response status is a redirection (3xx).
.expectRedirect()
Check for the existence and value of a cookie.
.expectCookie('session', 'abc123')
Ensure that a cookie contains a specific partial value.
.expectCookieContains('session', 'abc')
Create your own assertions with custom logic. This is helpful for more advanced testing scenarios.
.customAssertion((response) => {
expect(response.data.results).to.have.lengthOf.above(1);
});
In addition to the built-in assertions, SpecMate allows you to define your own custom assertions to extend the testing capabilities.
api.request('/users')
.withMethod('GET')
.customAssertion((response) => {
expect(response.data).to.have.property('results').with.length.greaterThan(1);
})
.run();
Check for the existence or value of cookies in the response.
.expectCookie('session', 'abc123')
.expectCookieContains('session', 'abc')
Here’s an example of using spec-mate with Nock to mock API responses for testing purposes:
import { SpecMate } from 'spec-mate';
import nock from 'nock';
describe('API Test Example with Nock', () => {
const api = new SpecMate('https://api.example.com');
beforeEach(() => {
nock.cleanAll();
nock.disableNetConnect();
});
it('should mock and validate a GET request', async () => {
// Mock GET /users API request
nock('https://api.example.com')
.get('/users')
.reply(200, {
results: [{ name: 'John Doe' }, { name: 'Jane Doe' }]
});
await api.request('/users')
.withMethod('GET')
.expectStatus(200)
.expectJsonPath('results[0].name', 'John Doe')
.run();
});
});
SpecMate provides hooks that allow you to run custom logic before or after a request is made.
Use the beforeRequest
hook to modify request headers, such as adding authentication tokens.
api.on('beforeRequest', (context) => {
context.headers['Authorization'] = `Bearer some-token`;
});
Run logic after the request is completed, such as logging the response.
api.on('afterRequest', (response) => {
console.log('Response received:', response.data);
});
This project is licensed under the MIT License. See the LICENSE file for more details.
spec-mate is developed and maintained by S25Digital
- mock-mate
For seamless API testing with mocked responses, check out mock-mate, another tool developed by S25Digital. mock-mate is designed to make API mocking simpler and more flexible, providing an easy way to create mock APIs that integrate perfectly with your spec-mate tests.
With mock-mate, you can:
- Create mock APIs based on OpenAPI specs.
- Pre-configure expected responses, headers, and status codes for different scenarios.
- Seamlessly integrate with spec-mate to test APIs in isolation without needing a live backend.
Use mock-mate in combination with spec-mate to create a complete testing suite for validating API functionality in controlled environments.