pact-foundation / jest-pact

A Pact adaptor for to allow you to easily run tests with Jest
https://pact.io
MIT License
80 stars 12 forks source link

Race condition #198

Closed jjdd12 closed 4 years ago

jjdd12 commented 4 years ago

I am facing a race condition issue. Sometimes the test passes, but more often than not it fails, since, the test runs before the provider adds the interaction, I figured out a few workarounds, however since my test looks a lot like the examples in the Readme, I'd like to know if I am doing something wrong, or if this is expected behavior here is my test:

        consumer: "client",
        provider: "api:,
        log: path.resolve(process.cwd(), "logs", "pact.log"),
        dir: path.resolve(process.cwd(), "pacts"),
        logLevel: "INFO"
    },
    provider => {
        let client;
        beforeEach(() =>
            client = api({options: {baseURL: provider.mockService.baseUrl}})
        )
        describe("get event by id", () => {
            beforeEach(() => {
                provider.addInteraction({
                    state: "event id exists",
                    uponReceiving: "a request for an event with id anid",
                    willRespondWith: {
                        status: 200,
                        body: userRsvp
                    },
                    withRequest: {
                        method: 'GET',
                        path: "/meal/5ec69049-72c3-4a6c-b418-8036559fa335"
                    }
                })
            })
            it("returns an array of userMeal objects", () => {
                client.getUserMeals("5ec69049-72c3-4a6c-b418-8036559fa335").then(
                    meals => expect(rsvps.data.length).toEqual(1)
                )
            });
        });
    })
TimothyJones commented 4 years ago

You need to wait on the promise that addInteraction returns. Change:

   beforeEach(() => {
                provider.addInteraction({

for:

   beforeEach(() =>  // note the implicit return instead of open brace
                provider.addInteraction({

alternatively you can use async/await. It's a matter of preference.

Note that your it function will have the same problem - the function will return before the expect is triggered. Either return a promise or await it to make sure that the test is asserting correctly.

I think I'll add a note to the readme to make this clearer.

(another source of brittle tests is running the tests in parallel - this occasionally causes failures when writing pacts. Make sure you're invoking jest with --runInBand)

I'll leave this open in case this doesn't fix your issue. Feel free to close it if it does.

jjdd12 commented 4 years ago

I think adding the note to the readme as you mentioned will be useful, thanks for your help

TimothyJones commented 4 years ago

You're welcome! Glad it worked out 👍