The SDET Playbook

← All questions

How do Pact provider state handlers set up database preconditions during provider verification runs?

Asked Sep 28, 2026Viewed 0 times

1 Answer

Sign in to answer and to vote.

  • 0
    The SDET PlaybookSep 28, 2026

    A consumer test names the state it assumes, such as .given('user 42 exists'). When the provider replays that interaction, the verifier first calls the state handler with the same name, which puts the provider's test data in place:

    const { Verifier } = require('@pact-foundation/pact');
    const { db } = require('./testDb'); // your provider's own test data helpers
    
    describe('UserService pact verification', () => {
      it('honours its consumers\' contracts', () => {
        return new Verifier({
          provider: 'UserService',
          providerBaseUrl: 'http://localhost:3000',
          pactBrokerUrl: process.env.PACT_BROKER_URL,
          providerVersion: process.env.GIT_SHA,
          providerVersionBranch: process.env.GIT_BRANCH,
          publishVerificationResult: !!process.env.CI,
          stateHandlers: {
            'user 42 exists': async () => {
              await db.users.upsert({ id: 42, name: 'John Doe', roles: ['MEMBER'] });
            },
            'no users exist': async () => {
              await db.users.deleteAll();
            },
          },
        }).verifyProvider();
      });
    });
    

    The provider runs against a test database, never a shared one. Each handler should set up exactly the state it names, whatever ran before it, so an upsert or a reset is safer than a plain insert. Agree on state names with consumer teams: the name is part of the contract, and a state the provider has no handler for will fail verification. A handler can also return values, such as a generated id, that the consumer marked with a provider-state matcher.

    Sources: Pact: provider states, Pact JS provider