liveBook · Manning

State handler

As explained in Contract Testing in Action

A state handler is a provider-side configuration or callback that establishes the data or conditions required for a provider state.

A provider contract verification can fail simply because the movie requested by a consumer does not exist. A state handler prepares that provider-side condition before verification runs, so the API can respond under the scenario described by the contract. section 6.3.2

In Pact, state handlers belong to the provider verifier options. Each handler name must exactly match a provider state declared by the consumer. The handler receives parameters, performs setup such as creating or modifying records, and can return a promise describing the change. Pact runs it before the contract interaction is verified. section 6.3.2 section 6.6

Preparing a movie for lookup

For a state named “Has a movie with specific ID,” the handler reads parameters.id, updates the first movie’s ID, and resolves with a description. The subsequent GET request can therefore retrieve the movie using the consumer’s chosen identifier. A different handler can delete every movie when the contract requires an empty database. section 6.3.2 section 12.3

const { importData, movies, server } = require('./provider')

...

'Has a movie with specific ID': (parameters) => {
   movies.getFirstMovie().id = parameters.id;
   return Promise.resolve({ description: `Movie with ID 
${parameters.id} added!` });
 }

Inspect the provider-side handler that applies the consumer’s movie ID and resolves a state-change description. section 6.3.2

A state handler establishes interaction data; it does not replace functional tests for the provider’s business rules. Keeping that boundary makes contract verification focused on compatibility with consumer expectations rather than exhaustive provider behavior. section 6.6

How Contract Testing in Action covers it

How deep it goes
Explains configuration, exact name matching, parameterized setup, execution order, and cleanup, but not broader business-rule testing.
Examples
Uses movie lookup by parameterized ID and database cleanup for an empty movie-list interaction.
What it assumes
Assumes consumer-defined provider states and Pact verification, while demonstrating the handler setup and matching rules.
What you can do after
Apply it via Pact stateHandlers to establish deterministic provider data before contract verification.
How it connects
Connects provider states with consumer-driven contract testing, Pact verification, integration testing, and functional testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Contract Testing in Action. The section links point to the parts of the book it draws on.