Let's get started by creating a simple service API. First, create a file route.js
module.exports = function (request, response) {
const payload = {
data: {
userId: 1,
id: 1,
title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
body: 'quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto'
}
};
response.status(200).json(payload);
};
Then, create a basic consumer contract file at contracts/example.contract.js
Contracts can be used in any environment, given that they are JSON Schema files. The example here shows testing in a node environment, with jest, to validate that your api satisfies a consumer contract.
Install dependencies:
npm install jest jest-json-schema supertest express --save-dev
Create a service.test.js file
const { matchers } = require('jest-json-schema');
const { load } = require('rivet');
const request = require('supertest');
const express = require('express');
const route = require('./route');
// add the jest-json-schema matchers to expect
expect.extend(matchers);
// setup the express app, with your new route
const app = express();
app.get('/example', route);
describe('My Api', () => {
it('satisfies the contract', () => {
// load the contract
const schema = load('example.contract');
request(app)
.get('/example')
.set('Accept', 'application/json')
.expect(200)
.then(response => {
// Validate the response with the contract
expect(response).toMatchSchema(schema);
});
});
});