docs/extend/scout/write-api-tests.md
Scout API tests validate HTTP endpoints with realistic scoped credentials.
:::::{important} Set up your plugin or package first. :::::
apiServices, kbnClient, esArchiver, …)requestAuth (or samlAuth for internal/* endpoints)apiClient + the scoped headersSee best practices for API tests.
Example test (Console).
For API tests, import expect from @kbn/scout/api or @kbn/scout-<solution>/api (more on solution-specific Scout packages).
Scout provides response matchers for apiClient responses and kbnClient.request(...) (Axios) responses:
toHaveStatusCode(200) (or toHaveStatusCode({ oneOf: [200, 201] }))toHaveStatusText('OK')toHaveHeaders({ 'content-type': 'application/json; charset=utf-8' }) (partial match; header keys are case-insensitive)These matchers do not apply to higher-level kbnClient.* helpers that return only data.
import type { RoleApiCredentials } from '@kbn/scout';
import { tags } from '@kbn/scout';
import { expect } from '@kbn/scout/api';
import { apiTest } from '../fixtures';
apiTest.describe('My endpoint', { tag: tags.deploymentAgnostic }, () => {
let viewerRoleCredentials: RoleApiCredentials;
apiTest.beforeAll(async ({ requestAuth }) => {
viewerRoleCredentials = await requestAuth.getApiKeyForViewer();
});
apiTest('returns JSON', async ({ apiClient }) => {
const res = await apiClient.get('api/my-plugin/endpoint', {
headers: { ...viewerRoleCredentials.apiKeyHeader, 'kbn-xsrf': 'scout' },
responseType: 'json',
});
expect(res).toHaveStatusCode(200);
expect(res).toHaveHeaders({ 'content-type': 'application/json; charset=utf-8' });
expect(res.body).toMatchObject({ ok: true });
});
});
API tests live under <plugin-root>/test/scout/api/tests and must end with .spec.ts.