|
| 1 | +import path from 'node:path'; |
| 2 | +import { |
| 3 | + type LogLevel, |
| 4 | + Matchers, |
| 5 | + Pact, |
| 6 | + SpecificationVersion, |
| 7 | +} from '@pact-foundation/pact'; |
| 8 | +import { describe, expect, it } from 'vitest'; |
| 9 | +import { fetchHello } from './consumer'; |
| 10 | + |
| 11 | +const { like } = Matchers; |
| 12 | + |
| 13 | +/** |
| 14 | + * Consumer Pact tests for the GraphQL Hello service. |
| 15 | + * |
| 16 | + * Pact treats GraphQL as a specialised form of HTTP: the interaction is still |
| 17 | + * a POST request, but `addGraphQLInteraction()` parses the query body and |
| 18 | + * normalises whitespace and field ordering when matching. You define the exact |
| 19 | + * GraphQL operation, variables, and expected response shape. |
| 20 | + * |
| 21 | + * Important: Pact verifies the GraphQL *contract* (request shape + response |
| 22 | + * shape), not the query logic. Use your GraphQL server's own tests for logic. |
| 23 | + */ |
| 24 | +describe('fetchHello — GraphQL consumer', () => { |
| 25 | + const pact = new Pact({ |
| 26 | + consumer: 'GraphQLConsumer', |
| 27 | + provider: 'GraphQLProvider', |
| 28 | + spec: SpecificationVersion.SPECIFICATION_VERSION_V4, |
| 29 | + dir: path.resolve(process.cwd(), 'pacts'), |
| 30 | + logLevel: (process.env.LOG_LEVEL as LogLevel) ?? 'warn', |
| 31 | + }); |
| 32 | + |
| 33 | + it('sends a HelloQuery and receives a greeting', async () => { |
| 34 | + await pact |
| 35 | + .addGraphQLInteraction() |
| 36 | + .given('the hello service is available') |
| 37 | + .uponReceiving('a HelloQuery request') |
| 38 | + // addGraphQLInteraction() wraps the operation details and generates |
| 39 | + // the correct POST body matcher automatically. |
| 40 | + .withOperation('HelloQuery') |
| 41 | + .withVariables({ name: 'World' }) |
| 42 | + .withRequest('POST', '/graphql') |
| 43 | + .withQuery(` |
| 44 | + query HelloQuery { |
| 45 | + hello |
| 46 | + } |
| 47 | + `) |
| 48 | + .willRespondWith(200, (builder) => { |
| 49 | + builder.headers({ 'Content-Type': 'application/json; charset=utf-8' }); |
| 50 | + // like() on the greeting string: the provider may return any greeting, |
| 51 | + // not specifically "Hello, World!". The contract only requires it to be |
| 52 | + // a string at data.hello. |
| 53 | + builder.jsonBody({ data: { hello: like('Hello, World!') } }); |
| 54 | + }) |
| 55 | + .executeTest(async (mockserver) => { |
| 56 | + const greeting = await fetchHello(mockserver.url); |
| 57 | + expect(greeting).toBe('Hello, World!'); |
| 58 | + }); |
| 59 | + }); |
| 60 | +}); |
0 commit comments