code-examples icon indicating copy to clipboard operation
code-examples copied to clipboard

Update pact javascript examples

Open TimothyJones opened this issue 4 years ago • 0 comments

Hi there,

I'm one of the pact maintainers, and we occasionally get people asking questions about the examples you have here, which (while instructive) have one or two bugs in the way that jest is used. Is it possible to update the examples to address these issues?

For instance, in the react example, this code doesn't correctly fail if the heroService throws an error, because the catch with done.fail isn't done at the end of the promise chain. This means the test doesn't trigger the appropriate failure in every error case. To address this, you could either move the done.fail part to the end of the promise chain, or return the promise to Jest instead of using done.

        it('sends a request according to contract', (done) => {
            heroService.createHero(new Hero('Superman', 'flying', 'DC'))
                .then(hero => {
                    expect(hero.id).toEqual(42);
                })
                .then(() => {
                    global.provider.verify()
                        .then(() => done(), error => {
                            done.fail(error)
                        })
                });
        });

Another issue is that the pact server is started on every test in jest-wrapper.js. This isn't a bug, but means that the log is quite noisy, which makes it harder to debug. For example, if the pact server starts correctly in a test that doesn't need it, but fails in a test that does, then this is not obvious from the current log. It's probably clearer to only start the server in pact tests.

You can get some of these improvements for free with jest-pact, which was introduced since this example was written, and substantially reduces the need for boilerplate in a jest test. See https://github.com/pact-foundation/jest-pact

You can also entirely avoid the need for publish.js by using the pact-broker CLI directly in your npm script - see: https://github.com/pact-foundation/pact-js#publish-in-npm-scripts

TimothyJones avatar Sep 27 '21 01:09 TimothyJones