REST Consumer and Provider Example
Explore testing a basic JavaScript client against the REST API, using a client library for contract testing.
We'll cover the following...
First, we will test a simple JavaScript client against the REST API provided by the Shopping Baskets module. We do not have a real UI to add tests to, but we can create a small JavaScript client library. For contract testing, we would only want to work with the client library anyhow, so this is not a big problem.
We will focus on a couple of endpoints for this demonstration:
const axios = require("axios");class Client {constructor(host = 'http://localhost:8080') {this.host = host;}startBasket(customerId) {return axios.post(`${this.host}/api/baskets`,{customerId})}addItem(basketId, productId, quantity = 1) {return axios.put(`${this.host}/api/baskets/${basketId}/addItem`,{productId, quantity})}}module.exports = {Client};
This JavaScript client is ready to be used in the latest single-page application (SPA) frontend and deployed to production. Before we deploy this client, it needs to be tested against the REST API.
Now, instead of starting up the real REST API server and running tests, we want to create individual interactions and test those against a mock provider. Then, we will use them to produce a contract that is shared with the provider so that it may verify every interaction from its point of view. We will be able to test these interactions just as swiftly as our unit tests.