Let's get started by creating a simple service API. First, create a file route.js
module.exports=function (request, response) {constpayload= { 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');constrequest=require('supertest');constexpress=require('express');constroute=require('./route');// add the jest-json-schema matchers to expectexpect.extend(matchers);// setup the express app, with your new routeconstapp=express();app.get('/example', route);describe('My Api', () => {it('satisfies the contract', () => {// load the contractconstschema=load('example.contract');request(app).get('/example').set('Accept','application/json').expect(200).then(response => {// Validate the response with the contractexpect(response).toMatchSchema(schema); }); });});