2.0.0 ⢠Published 10 months ago
pact-mock-js v2.0.0
pact-mock-js
pact-mock-js
is a Node.js library that allows you to build Pact contracts by leveraging your existings mocks. It could be used with your existing mocks defined with msw or Cypress. This library provides an easy way to generate contracts that can be used for testing and verifying API interactions between consumer and provider.
Install
yarn add -D pact-mock-js
Getting started with MSW
Here is an example of how to use pact-mock-js with MSW:
import { setupServer, rest } from 'msw/node'
import { Pact } from 'pact-mock-js/msw'
import { writeFile } from 'fs'
const server = setupServer()
const pact = new Pact({
consumer: { name: 'test-consumer' },
provider: { name: 'rest-provider' },
metadata: { pactSpecification: { version: '2.0.0' } },
})
beforeAll(() => {
server.listen()
pact.reset()
})
afterEach(() => {
server.resetHandlers()
})
afterAll(() => {
server.close()
// Write the pact file wherever you want
fs.writeFile(
`pacts/${pact.name}.json`,
JSON.stringify(pact.generatePactFile())
)
})
it('get all movies', async () => {
const mockMovies = rest.get(
'*/movies',
pact.toResolver({
description: 'a request to list all movies',
response: [
{
id: 1,
name: 'Movie 1',
year: 2008,
},
{
id: 2,
name: 'Movie 2',
year: 2008,
},
],
})
)
server.use(mockMovies)
const movies = await fetchMovies()
expect(movies).toEqual([
{
id: 1,
name: 'Movie 1',
year: 2008,
},
{
id: 2,
name: 'Movie 2',
year: 2008,
},
])
})
You can find more example to mock
Getting started with Cypress
Here is an example of how to use pact-mock-js with Cypress:
import { Pact } from 'pact-mock-js/cypress'
const server = setupServer()
const pact = new Pact({
consumer: { name: 'test-consumer' },
provider: { name: 'rest-provider' },
metadata: { pactSpecification: { version: '2.0.0' } },
})
before(() => {
pact.reset()
})
after(() => {
// Write the pact file wherever you want
cy.writeFile(`pacts/${pact.name}.json`, pact.generatePactFile())
})
it('get all movies', async () => {
// intercept and mock the movies response while record the interaction
cy.intercept(
'GET',
`/*/movies`,
pact.toHandler({
description: 'a request to list all movies',
response: [
{
id: 1,
name: 'Movie 1',
year: 2008,
},
{
id: 2,
name: 'Movie 2',
year: 2008,
},
],
})
).as('multipleMovies')
// open the page to test
cy.visit('/')
// add your assertions
cy.wait('@multipleMovies')
.its('response')
.its('statusCode')
.should('be.equal', 200)
})
You can find more example to mock
Author
š¤ Ludovic Dorival
- Github: @ludorival
Show your support
Give a āļø if this project helped you!
š License
Copyright Ā© 2021 Ludovic Dorival. This project is BSD--3--Clause licensed.
This README was generated with ā¤ļø by readme-md-generator