Open lhokktyn opened 10 months ago
Tweaking this a little to turn provider
into a factory function, so generating a new PactV4
instance for every interaction, seems to resolve the issue:
import { PactV4, SpecificationVersion, MatchersV3 } from "@pact-foundation/pact";
const { string, number, regex } = MatchersV3;
const provider = () => new PactV4({
consumer: "consumer",
provider: "provider",
spec: SpecificationVersion.SPECIFICATION_VERSION_V4,
logLevel: "fatal",
});
const test1 = async () => {
const petId = "one";
await provider()
.addInteraction()
.uponReceiving("a request for a pet with an invalid ID")
.withRequest('get', regex("/pet/[a-z]+", `/pet/${petId}`), (builder) => builder
.headers({ Accept: "application/json" })
)
.willRespondWith(400, (builder) => builder
.headers({ "content-type": "application/json" })
.jsonBody({
code: number(1),
type: string("error"),
message: string("Invalid ID supplied"),
})
)
.executeTest(async (mockserver) => {
await fetch(`${mockserver.url}/pet/${petId}`, {
headers: {
Accept: "application/json",
},
});
});
};
const test2 = async () => {
const petId = 100;
await provider()
.addInteraction()
.given("no pets exist")
.uponReceiving("a request for a pet with an ID")
.withRequest('get', regex("/pet/[0-9]+", `/pet/${petId}`), (builder) => builder
.headers({ Accept: "application/json" })
)
.willRespondWith(404, (builder) => builder
.headers({ "content-type": "text/plain" })
)
.executeTest(async (mockserver) => {
await fetch(`${mockserver.url}/pet/${petId}`, {
headers: {
Accept: "application/json",
},
});
});
};
const delay = (t) => new Promise((r) => setTimeout(r, t));
try {
await test1();
// await delay(1000); // not needed
await test2();
} catch(e) {
console.log(e.message);
}
And both interactions are written to the same pact json without conflict. So problem solved ... but is the correct approach? The example I was following is 3 months old at the time of writing, so perhaps things have moved on?
Software versions
Please provide at least OS and version of pact-js
@pact-foundation/pact@12.1.0
18.13.0
Issue Checklist
Please confirm the following:
Expected behaviour
When more than one interaction is tested with
pact.addInteraction()...executeTest()
, both tests pass without error.Actual behaviour
The first test passes, but the next one fails with the error:
Pact appears to be re-driving the first interaction, so in subsequent
executeTest()
calls the mock server is receiving the wrong request.This feels like user error, but for the life of me I'm not seeing where I've gone wrong! The docs all appear to be geared around V3 at the moment whilst V4 support is in beta, so I've been using examples such as this one to pull things together.
Steps to reproduce
Minimal-ish script to replicate (
replicate.js
):Run with:
To confirm behaviour with a single test running, comment out
await test1()
and re-run - it should pass with no error.Relevant log files
Minimal logs:
Full debug logs: