The SDET Playbook

← All questions

How do you construct a Pact consumer test in JavaScript using flexible type matchers?

Asked Sep 28, 2026Viewed 0 times

1 Answer

Sign in to answer and to vote.

  • 0
    The SDET PlaybookSep 28, 2026

    Matchers make the contract check the type and shape of a value rather than the exact example, so the provider can return any user with the right structure. like() matches by type, and eachLike() matches an array whose items all look like the example. The interaction is only recorded when you call your real client code inside executeTest, against Pact's mock server:

    const { PactV3, MatchersV3 } = require('@pact-foundation/pact');
    const { like, eachLike } = MatchersV3;
    const { UserClient } = require('./userClient');
    
    const provider = new PactV3({ consumer: 'FrontendApp', provider: 'UserService' });
    
    describe('UserClient', () => {
      it('fetches a user profile', () => {
        provider
          .given('user 42 exists')
          .uponReceiving('a request for user 42')
          .withRequest({ method: 'GET', path: '/users/42' })
          .willRespondWith({
            status: 200,
            headers: { 'Content-Type': 'application/json' },
            body: {
              id: like(42),
              name: like('John Doe'),
              roles: eachLike('MEMBER'),
            },
          });
    
        return provider.executeTest(async (mockServer) => {
          const user = await new UserClient(mockServer.url).getUser(42);
          expect(user.name).toBe('John Doe');
        });
      });
    });
    

    When the test passes, Pact writes the pact file (by default to ./pacts), which you publish to the broker for the provider to verify. Only include the fields your client actually reads: every field in the contract is one the provider can no longer remove freely. Use exact values only where the exact value matters, such as a status field.

    Sources: Pact JS consumer, Pact JS matching