Gathering detailed insights and metrics for @pactflow/pact-msw-adapter
Gathering detailed insights and metrics for @pactflow/pact-msw-adapter
Gathering detailed insights and metrics for @pactflow/pact-msw-adapter
Gathering detailed insights and metrics for @pactflow/pact-msw-adapter
@pactflow/pact-cypress-adapter
A cypress adapter for pact
msw
Seamless REST/GraphQL API mocking library for browser and Node.js.
@pact-foundation/pact-core
Core of @pact-foundation/pact. You almost certainly don't want to depend on this directly.
@pact-foundation/pact
Pact for all things Javascript
Create MSW (mock-service-worker) mocks, and generate pact contracts from the recorded interactions.
npm install @pactflow/pact-msw-adapter
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
45 Stars
226 Commits
15 Forks
12 Watching
23 Branches
8 Contributors
Updated on 19 Oct 2024
Minified
Minified + Gzipped
TypeScript (70.78%)
Shell (27.8%)
JavaScript (1.22%)
Makefile (0.2%)
Cumulative downloads
Total Downloads
Last day
49.4%
2,581
Compared to previous day
Last week
4.2%
28,712
Compared to previous week
Last month
4%
128,232
Compared to previous month
Last year
255.9%
942,253
Compared to previous year
Generate pact contracts from the recorded mock service worker interactions.
Check out the quick start guide.
pact msw version | msw version | node version | migration guide |
---|---|---|---|
^2 | <=1 | >=16 <=20 | |
^3 | ^2 | >=18 | v2 to v3 |
npm install @pactflow/pact-msw-adapter --save-dev
or yarn
yarn add -D @pactflow/pact-msw-adapter
MSW provides a setupServer
for node environments and setupWorker
for browser based environment
1import { setupServer } from "msw/node"; 2import { setupPactMswAdapter } from "@pactflow/pact-msw-adapter";
For browser based enviromnents
1import { setupWorker } from "msw/browser"; 2import { setupPactMswAdapter } from "@pactflow/pact-msw-adapter";
See ./src/pactFromMswServer.msw.spec.ts msw mock server example (jest/msw/react)
See ./examples/react/cypress/integration/pactFromMswWorker.spec.js msw mock worker example (cypress/msw/react)
These tests will generate pacts, which can be found in the ./msw_generated_pacts
folder
Let's start by listing it's methods:
setupPactMswAdapter
: Generates an pact-msw-adapter instance. It also allows for several options on the adapter.newTest
: Tells the adapter a new test is about to start. This is used for validating msw calls.verifyTest
: Waits for all pending network calls to finish or timeout, and asserts that all these calls started and finished on the same test without unexpected errors, and that there were no calls to included urls which aren't handled by msw.clear
: Resets all pact-msw-adapter's internal states, same effect as generating a new pact-msw-adapter instance.writeToFile
: Dumps all the recorded msw calls to pact files, generating one pact file for each consumer-provider call. For browser environments, it requires a custom file writter as argument.Parameter | Required? | Type | Default | Description |
---|---|---|---|---|
server | false | SetupServer | server provided by msw - a server or worker must be provided | |
worker | false | SetupWorker | worker provided by msw - a server or worker must be provided | |
timeout | false | number | 200 | Time in ms for a network request to expire, verifyTest will fail after twice this amount of time. |
consumer | true | string | name of the consumer running the tests | |
providers | true | { [string]: string[] } | ({ request: Request; requestId: string }) => string | null | names and filters for each provider or function that returns name of provider for given request | |
pactOutDir | false | string | ./msw_generated_pacts/ | path to write pact files into |
includeUrl | false | string[] | inclusive filters for network calls | |
excludeUrl | false | string[] | exclusive filters for network calls | |
excludeHeaders | false | string[] | exclude generated headers from being written to request/response objects in pact file | |
debug | false | boolean | false | prints verbose information about pact-msw-adapter events |
logger | false | console | console | logger used to print messages to console |
By default pact-msw-adapter will try to record an interaction for every single network call, including external dependencies, fonts or static resources. This is why we’re implementing a route filtering mechanism to include only relevant paths in our pact files.
This mechanism has three layers, in order of priority:
excludeUrl
: All paths containing any of the strings present in this array will be ignored.includeUrl
: All paths not containing any of the strings in this array will be ignored.providers
: Paths not containing any of the strings listed in the map’s values will be ignored.The first two layers can be skipped by setting it’s value to undefined
. The third layer is mandatory.
providers
can be also a function that returns name of provider for given request. If no provider is matched it should return null
. This allows dynamically matching providers based on url patterns.
By default pact-msw-adapter captures and serialises all request and response headers captured, in the generated pact file.
You may wish to exclude these on a global basis.
This mechanism currently has a layer
excludeHeaders
: All headers containing any of the strings present in this array will be ignored.The adapter uses by default node’s filesystem to write pact files to disk. This makes it incompatible with browser environments where fs
is not available. To overcome this, pact-msw-adapter
allows for defining custom functions for writting files to disk.
1writeToFile(writer?: (path: string, data: object) => void): Promise<void>
Writers are required to by synchronous.
The path
argument contains a relative path to save the file into, already prepending pactOutDir
, and including the file’s name and extension.
The data
field consists of a javascript object containing a pact file (check the anatomy of a pact file).
You can create your own instance of a Logger
, the default is a console
If one wishes to suppress the output from pact-msw-adapter, you could use the following emptyConsole
function.
1 const emptyConsole = () => { 2 const emptyFunction = () => {}; 3 const emptyConsole = { 4 log: emptyFunction, 5 debug: emptyFunction, 6 info: emptyFunction, 7 warn: emptyFunction, 8 error: emptyFunction, 9 group: emptyFunction, 10 groupCollapsed: emptyFunction, 11 groupEnd: emptyFunction, 12 }; 13 return emptyConsole; 14 }
Pass the custom console to the options.logger
key in setupPactMswAdapter
1import { PactFile, setupPactMswAdapter } from "./pactMswAdapter";
2
3const server = setupServer();
4const pactMswAdapter = setupPactMswAdapter({
5 server,
6 options: {
7 ...options,
8 logger: emptyConsole()
9 },
10});
Note: - This will not control or affect msw's native logging.
pact-msw-adapter
will dump all the recorded requests into pact files when writeToFile
is called.
A recorded request is a request which has started and been successfully mocked by msw since pact-msw-adapter has been instantiated or cleared. This can include duplicated requests and does not distinguishes between different test runs.
Each time writeToFile
is run, it will generate one pact file for every consumer-provider pair. In practice, consumers are fixed, making it to generate one pact file per provider.
In order to do this, pact-msw-adapter
uses the providers map to asociate a request with a provider. The providers map is iterated in order and each request is associated with exactly one provider.
Once this association is done, pact-msw-adapter
will translate each request to a pact interaction and group these interactions on pact files by provider.
1import { setupPactMswAdapter } from '@pactflow/pact-msw-adapter';
2
3let pactMswAdapter: any = undefined;
4
5beforeEach(async () => {
6 if (!pactMswAdapter) {
7 cy.window().then(window => {
8 pactMswAdapter = setupPactMswAdapter({
9 worker: window.msw.worker,
10 options: {
11 consumer: 'web-ea',
12 timeout: 1000,
13 providers: {
14 'edge-api-admin': [ 'edge-api-admin' ]
15 },
16 pactOutDir: './pacts',
17 excludeUrl: ['static/'],
18 // debug: true
19 },
20 });
21 pactMswAdapter.newTest();
22 });
23 } else {
24 pactMswAdapter.newTest();
25 }
26});
27afterEach(async () => {
28 if (!pactMswAdapter) return;
29
30 try {
31 await pactMswAdapter.verifyTest();
32 } catch (err) {
33 // cypress doesn't like errors on hooks...
34 if (process.env.NODE_ENV !== 'production') {
35 console.groupCollapsed('%cError generating pacts.', 'color:coral;font-weight:bold;');
36 console.log(err);
37 console.groupEnd();
38 } else {
39 // fail on pipelines
40 throw err;
41 }
42 }
43});
44after(async () => {
45 if (!pactMswAdapter) return;
46
47 await pactMswAdapter.writeToFile((path: string, data: object) => cy.writeFile(path, data));
48 pactMswAdapter.clear();
49});
Without further do, it looks like the following:
1{ 2 "consumer": { "name": "" }, 3 "provider": { "name": "" }, 4 "interactions": [ 5 { 6 "description": "", 7 "providerState": "", 8 "request": { 9 "method": "GET", 10 "path": "", // Ids replaced 11 "query": "", // url-encoded query 12 "matchingRules": { ... } 13 }, 14 "response": { 15 "status": 200, 16 "headers": { }, 17 "body": { ... }, 18 "matchingRules": { ... } 19 } 20 } 21 ], 22 "metadata": { 23 "pactSpecification": { 24 "version": "2.0.0" 25 } 26 } 27}
Here, matchingRules
represent the assertions of the expectation, while body
, query
and path
contains it's example values.
In October 2023 msw released new version 2 that bring significant changes to the msw interface. To reflect these changes we've released pact-msw-adapter@v3 that's compatible with msw@v2.
To migrate you'll need to update msw to >=2.0
and migrate your usage of the library (migration guide here).
Breaking changes on pact-msw-adapter side:
MswMatch
is now MatchedRequest
and is { request: Request; requestId: string; response: Response }
ExpiredRequest
still called the same and is { request: Request; requestId: string; startTime: number; duration?: number }
PendingRequest
as { request: Request; requestId: string; }
PactMswAdapterOptions.providers
function variant is now consistent with msw and has signature (event: PendingRequest) => string | null
PactMswAdapter.emitter
events are slightly updated to match msw behaviour
pact-msw-adapter:expired
handler must have signature (event: ExpiredRequest) => void
pact-msw-adapter:match
handler must have signature (event: MatchedRequest) => void
convertMswMatchToPact
is now async functionBackground:
Made possible by these awesome people! You are welcome to contribute too!
Special thanks to Juan Cruz for being an early adopter and improving the experience!
No vulnerabilities found.
No security vulnerabilities found.