debian-mirror-gitlab/doc/development/testing_guide/contract/consumer_tests.md

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

320 lines
11 KiB
Markdown
Raw Normal View History

2022-07-23 23:45:48 +05:30
---
stage: none
group: Development
2022-11-25 23:54:43 +05:30
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/product/ux/technical-writing/#assignments
2022-07-23 23:45:48 +05:30
---
# Writing consumer tests
2023-03-17 16:20:25 +05:30
This tutorial guides you through writing a consumer test from scratch. To start, the consumer tests are written using [`jest-pact`](https://github.com/pact-foundation/jest-pact) that builds on top of [`pact-js`](https://github.com/pact-foundation/pact-js). This tutorial shows you how to write a consumer test for the `/discussions.json` REST API endpoint, which is `/:namespace_name/:project_name/-/merge_requests/:id/discussions.json`, that is called in the `MergeRequests#show` page. For an example of a GraphQL consumer test, see [`spec/contracts/consumer/specs/project/pipelines/show.spec.js`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/spec/contracts/consumer/specs/project/pipelines/show.spec.js).
2022-07-23 23:45:48 +05:30
## Create the skeleton
2023-03-17 16:20:25 +05:30
Start by creating the skeleton of a consumer test. Since this is for a request in the `MergeRequests#show` page, under `spec/contracts/consumer/specs/project/merge_requests`, create a file called `show.spec.js`.
2022-07-23 23:45:48 +05:30
Then, populate it with the following function and parameters:
- [`pactWith`](#the-pactwith-function)
- [`PactOptions`](#the-pactoptions-parameter)
- [`PactFn`](#the-pactfn-parameter)
2023-04-23 21:23:45 +05:30
For more information about how the contract test directory is structured, see [Test suite folder structure](index.md#test-suite-folder-structure).
2022-08-13 15:12:31 +05:30
2022-07-23 23:45:48 +05:30
### The `pactWith` function
The Pact consumer test is defined through the `pactWith` function that takes `PactOptions` and the `PactFn`.
```javascript
2022-08-27 11:52:29 +05:30
import { pactWith } from 'jest-pact';
2022-07-23 23:45:48 +05:30
pactWith(PactOptions, PactFn);
```
### The `PactOptions` parameter
`PactOptions` with `jest-pact` introduces [additional options](https://github.com/pact-foundation/jest-pact/blob/dce370c1ab4b7cb5dff12c4b62246dc229c53d0e/README.md#defaults) that build on top of the ones [provided in `pact-js`](https://github.com/pact-foundation/pact-js#constructor). In most cases, you define the `consumer`, `provider`, `log`, and `dir` options for these tests.
```javascript
2022-08-27 11:52:29 +05:30
import { pactWith } from 'jest-pact';
2022-07-23 23:45:48 +05:30
pactWith(
{
2023-03-17 16:20:25 +05:30
consumer: 'MergeRequests#show',
provider: 'GET discussions',
2022-07-23 23:45:48 +05:30
log: '../logs/consumer.log',
2023-03-17 16:20:25 +05:30
dir: '../contracts/project/merge_requests/show',
2022-07-23 23:45:48 +05:30
},
PactFn
);
```
2023-04-23 21:23:45 +05:30
For more information about how to name consumers and providers, see [Naming conventions](index.md#naming-conventions).
2022-08-13 15:12:31 +05:30
2022-07-23 23:45:48 +05:30
### The `PactFn` parameter
The `PactFn` is where your tests are defined. This is where you set up the mock provider and where you can use the standard Jest methods like [`Jest.describe`](https://jestjs.io/docs/api#describename-fn), [`Jest.beforeEach`](https://jestjs.io/docs/api#beforeeachfn-timeout), and [`Jest.it`](https://jestjs.io/docs/api#testname-fn-timeout). For more information, see [https://jestjs.io/docs/api](https://jestjs.io/docs/api).
```javascript
2022-08-27 11:52:29 +05:30
import { pactWith } from 'jest-pact';
2022-07-23 23:45:48 +05:30
pactWith(
{
2023-03-17 16:20:25 +05:30
consumer: 'MergeRequests#show',
provider: 'GET discussions',
2022-07-23 23:45:48 +05:30
log: '../logs/consumer.log',
2023-03-17 16:20:25 +05:30
dir: '../contracts/project/merge_requests/show',
2022-07-23 23:45:48 +05:30
},
(provider) => {
2023-03-17 16:20:25 +05:30
describe('GET discussions', () => {
2022-07-23 23:45:48 +05:30
beforeEach(() => {
2022-08-13 15:12:31 +05:30
2022-07-23 23:45:48 +05:30
});
2022-08-27 11:52:29 +05:30
it('return a successful body', async () => {
2022-08-13 15:12:31 +05:30
2022-07-23 23:45:48 +05:30
});
});
},
);
```
## Set up the mock provider
Before you run your test, set up the mock provider that handles the specified requests and returns a specified response. To do that, define the state and the expected request and response in an [`Interaction`](https://github.com/pact-foundation/pact-js/blob/master/src/dsl/interaction.ts).
For this tutorial, define four attributes for the `Interaction`:
1. `state`: A description of what the prerequisite state is before the request is made.
1. `uponReceiving`: A description of what kind of request this `Interaction` is handling.
1. `withRequest`: Where you define the request specifications. It contains the request `method`, `path`, and any `headers`, `body`, or `query`.
1. `willRespondWith`: Where you define the expected response. It contains the response `status`, `headers`, and `body`.
After you define the `Interaction`, add that interaction to the mock provider by calling `addInteraction`.
```javascript
2022-08-27 11:52:29 +05:30
import { pactWith } from 'jest-pact';
import { Matchers } from '@pact-foundation/pact';
2022-07-23 23:45:48 +05:30
pactWith(
{
2023-03-17 16:20:25 +05:30
consumer: 'MergeRequests#show',
provider: 'GET discussions',
2022-07-23 23:45:48 +05:30
log: '../logs/consumer.log',
2023-03-17 16:20:25 +05:30
dir: '../contracts/project/merge_requests/show',
2022-07-23 23:45:48 +05:30
},
(provider) => {
2023-03-17 16:20:25 +05:30
describe('GET discussions', () => {
2022-07-23 23:45:48 +05:30
beforeEach(() => {
const interaction = {
state: 'a merge request with discussions exists',
uponReceiving: 'a request for discussions',
withRequest: {
method: 'GET',
path: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: {
Accept: '*/*',
},
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: Matchers.eachLike({
id: Matchers.string('fd73763cbcbf7b29eb8765d969a38f7d735e222a'),
project_id: Matchers.integer(6954442),
...
resolved: Matchers.boolean(true)
}),
},
};
provider.addInteraction(interaction);
});
2022-08-27 11:52:29 +05:30
it('return a successful body', async () => {
2022-07-23 23:45:48 +05:30
});
});
},
);
```
### Response body `Matchers`
2022-08-27 11:52:29 +05:30
Notice how we use `Matchers` in the `body` of the expected response. This allows us to be flexible enough to accept different values but still be strict enough to distinguish between valid and invalid values. We must ensure that we have a tight definition that is neither too strict nor too lax. Read more about the [different types of `Matchers`](https://github.com/pact-foundation/pact-js/blob/master/docs/matching.md). We are currently using the V2 matching rules.
2022-07-23 23:45:48 +05:30
## Write the test
After the mock provider is set up, you can write the test. For this test, you make a request and expect a particular response.
2022-08-27 11:52:29 +05:30
First, set up the client that makes the API request. To do that, create `spec/contracts/consumer/resources/api/project/merge_requests.js` and add the following API request. If the endpoint is a GraphQL, then we create it under `spec/contracts/consumer/resources/graphql` instead.
2022-07-23 23:45:48 +05:30
```javascript
2022-08-27 11:52:29 +05:30
import axios from 'axios';
export async function getDiscussions(endpoint) {
const { url } = endpoint;
return axios({
method: 'GET',
baseURL: url,
url: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: { Accept: '*/*' },
})
}
2022-07-23 23:45:48 +05:30
```
After that's set up, import it to the test file and call it to make the request. Then, you can make the request and define your expectations.
```javascript
2022-08-27 11:52:29 +05:30
import { pactWith } from 'jest-pact';
import { Matchers } from '@pact-foundation/pact';
2022-07-23 23:45:48 +05:30
2022-08-27 11:52:29 +05:30
import { getDiscussions } from '../../../resources/api/project/merge_requests';
2022-07-23 23:45:48 +05:30
pactWith(
{
2023-03-17 16:20:25 +05:30
consumer: 'MergeRequests#show',
provider: 'GET discussions',
2022-07-23 23:45:48 +05:30
log: '../logs/consumer.log',
2023-03-17 16:20:25 +05:30
dir: '../contracts/project/merge_requests/show',
2022-07-23 23:45:48 +05:30
},
(provider) => {
2023-03-17 16:20:25 +05:30
describe('GET discussions', () => {
2022-07-23 23:45:48 +05:30
beforeEach(() => {
const interaction = {
state: 'a merge request with discussions exists',
uponReceiving: 'a request for discussions',
withRequest: {
method: 'GET',
path: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: {
Accept: '*/*',
},
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: Matchers.eachLike({
id: Matchers.string('fd73763cbcbf7b29eb8765d969a38f7d735e222a'),
project_id: Matchers.integer(6954442),
...
resolved: Matchers.boolean(true)
}),
},
};
});
2022-08-27 11:52:29 +05:30
it('return a successful body', async () => {
const discussions = await getDiscussions({
2022-07-23 23:45:48 +05:30
url: provider.mockService.baseUrl,
});
2023-01-13 00:05:48 +05:30
2022-08-27 11:52:29 +05:30
expect(discussions).toEqual(Matchers.eachLike({
id: 'fd73763cbcbf7b29eb8765d969a38f7d735e222a',
project_id: 6954442,
...
resolved: true
}));
2022-07-23 23:45:48 +05:30
});
});
},
);
```
There we have it! The consumer test is now set up. You can now try [running this test](index.md#run-the-consumer-tests).
## Improve test readability
As you may have noticed, the request and response definitions can get large. This results in the test being difficult to read, with a lot of scrolling to find what you want. You can make the test easier to read by extracting these out to a `fixture`.
2023-03-17 16:20:25 +05:30
Create a file under `spec/contracts/consumer/fixtures/project/merge_requests` called `discussions.fixture.js` where you will place the `request` and `response` definitions.
2022-07-23 23:45:48 +05:30
```javascript
2022-08-27 11:52:29 +05:30
import { Matchers } from '@pact-foundation/pact';
2022-07-23 23:45:48 +05:30
const body = Matchers.eachLike({
id: Matchers.string('fd73763cbcbf7b29eb8765d969a38f7d735e222a'),
project_id: Matchers.integer(6954442),
...
resolved: Matchers.boolean(true)
});
const Discussions = {
body: Matchers.extractPayload(body),
success: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
2022-08-27 11:52:29 +05:30
body,
2022-07-23 23:45:48 +05:30
},
2022-08-27 11:52:29 +05:30
scenario: {
state: 'a merge request with discussions exists',
2022-07-23 23:45:48 +05:30
uponReceiving: 'a request for discussions',
2022-08-27 11:52:29 +05:30
},
request: {
2022-07-23 23:45:48 +05:30
withRequest: {
method: 'GET',
path: '/gitlab-org/gitlab-qa/-/merge_requests/1/discussions.json',
headers: {
Accept: '*/*',
},
},
},
};
exports.Discussions = Discussions;
```
With all of that moved to the `fixture`, you can simplify the test to the following:
```javascript
2022-08-27 11:52:29 +05:30
import { pactWith } from 'jest-pact';
2023-03-17 16:20:25 +05:30
import { Discussions } from '../../../fixtures/project/merge_requests/discussions.fixture';
2022-08-27 11:52:29 +05:30
import { getDiscussions } from '../../../resources/api/project/merge_requests';
2022-07-23 23:45:48 +05:30
2023-03-17 16:20:25 +05:30
const CONSUMER_NAME = 'MergeRequests#show';
const PROVIDER_NAME = 'GET discussions';
2022-08-27 11:52:29 +05:30
const CONSUMER_LOG = '../logs/consumer.log';
2023-03-17 16:20:25 +05:30
const CONTRACT_DIR = '../contracts/project/merge_requests/show';
2022-07-23 23:45:48 +05:30
pactWith(
{
2022-08-27 11:52:29 +05:30
consumer: CONSUMER_NAME,
provider: PROVIDER_NAME,
log: CONSUMER_LOG,
dir: CONTRACT_DIR,
2022-07-23 23:45:48 +05:30
},
(provider) => {
2022-08-27 11:52:29 +05:30
describe(PROVIDER_NAME, () => {
2022-07-23 23:45:48 +05:30
beforeEach(() => {
const interaction = {
2022-08-27 11:52:29 +05:30
...Discussions.scenario,
2022-07-23 23:45:48 +05:30
...Discussions.request,
willRespondWith: Discussions.success,
};
2022-08-27 11:52:29 +05:30
provider.addInteraction(interaction);
2022-07-23 23:45:48 +05:30
});
2022-08-27 11:52:29 +05:30
it('return a successful body', async () => {
const discussions = await getDiscussions({
2022-07-23 23:45:48 +05:30
url: provider.mockService.baseUrl,
});
2022-08-27 11:52:29 +05:30
expect(discussions).toEqual(Discussions.body);
2022-07-23 23:45:48 +05:30
});
});
},
);
```