REST API
Beginner
1 min read
Contract Testing with Pact
Example
// npm install @pact-foundation/pact
// Consumer test (frontend / API client)
import { Pact } from '@pact-foundation/pact';
import { like, eachLike, term } from '@pact-foundation/pact/src/dsl/matchers';
const provider = new Pact({
consumer: 'WebApp',
provider: 'ProductsAPI',
port: 1234,
log: './pacts/logs/pact.log',
dir: './pacts',
});
describe('Products API contract', () => {
before(() => provider.setup());
after(() => provider.finalize());
it('returns a list of products', async () => {
await provider.addInteraction({
state: 'products exist',
uponReceiving: 'a request for products',
withRequest: { method: 'GET', path: '/api/v1/products',
headers: { Authorization: like('Bearer token') } },
willRespondWith: {
status: 200,
body: {
data: eachLike({
id: like(1),
name: like('Running Shoes'),
price: like(89.99),
}),
meta: { total: like(10) },
},
},
});
const products = await fetchProducts('Bearer token');
expect(products.data[0]).toHaveProperty('name');
});
});
// Provider verification (in ProductsAPI CI)
// const { Verifier } = require('@pact-foundation/pact');
// new Verifier({ provider: 'ProductsAPI', pactUrls: ['./pacts/WebApp-ProductsAPI.json'],
// providerBaseUrl: 'http://localhost:8000' }).verifyProvider();
Related Resources
This is the last lesson in this section.
Create a free account to earn a certificate