@gitlab/frontend-tests 0.1.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -49,7 +49,9 @@ This package holds the framework core of GitLab's frontend integration tests. Th
49
49
 
50
50
  `@gitlab/frontend-tests/integration/polyfills/text-encoding` and `@gitlab/frontend-tests/integration/polyfills` are Jest `setupFiles` entries, in that order. The first puts `TextEncoder` and `TextDecoder` on `global`. The second adds the web streams, `BroadcastChannel`, and `fetch`, `Request`, `Response` and `Headers` from `@whatwg-node/fetch`.
51
51
 
52
- `@gitlab/frontend-tests/integration/jest-config` exports `createFrontendIntegrationConfig(config)` and `MSW_ESM_DEPENDENCIES`.
52
+ `@gitlab/frontend-tests/integration/jest-config` exports `createFrontendIntegrationConfig(config)`, `MSW_ESM_DEPENDENCIES` and `APOLLO_ESM_DEPENDENCIES`.
53
+
54
+ `@gitlab/frontend-tests/integration/setup-budget` and `@gitlab/frontend-tests/integration/setup-budget-lint` are described in [Wait budgets](#wait-budgets).
53
55
 
54
56
  ### Jest configuration
55
57
 
@@ -67,7 +69,8 @@ module.exports = createFrontendIntegrationConfig({
67
69
 
68
70
  The factory changes these things:
69
71
 
70
- - Adds the ESM-only dependencies of msw (`rettime`, `until-async`, `@open-draft/*`) to the `transformIgnorePatterns` allowlist.
72
+ - Adds the ESM-only dependencies of msw (`MSW_ESM_DEPENDENCIES`: `rettime`, `until-async`, `@open-draft/*`) and of Apollo (`APOLLO_ESM_DEPENDENCIES`: `@apollo/client`, `@vue/apollo-composable`, `ts-invariant`) to the `transformIgnorePatterns` allowlist. It extends a pnpm allowlist (`node_modules/\.pnpm/(?!(a|b)@)`) or a flat npm/Yarn one (`node_modules/(?!(a|b)/)`). It throws when no pattern has either shape, and leaves the other entries of your allowlist as they are. With pnpm, use the pnpm shape: the factory adds pnpm paths for its own dependencies to a flat allowlist, but your entries in it never match pnpm paths.
73
+ - Adds a `babel-jest` transform for `.mjs` files, which the dependencies above ship. A `'^.+\.mjs$'` transform in your config wins. When your config has no `transform`, the factory also adds Jest's default `'\.[jt]sx?$': 'babel-jest'`, because Jest drops its default as soon as any `transform` key is set.
71
74
  - Appends the two polyfills entries to `setupFiles`, text encoding first.
72
75
  - Clears `testPathIgnorePatterns`.
73
76
  - Disables global fake timers.
@@ -75,7 +78,69 @@ The factory changes these things:
75
78
 
76
79
  It does not touch `setupFilesAfterEnv`, module aliases or the test environment. Those stay with the consumer.
77
80
 
78
- `msw` v2 is a peer dependency, and `@jest/types` is an optional peer that only TypeScript consumers of `jest-config` need. `@whatwg-node/fetch` is the only regular dependency; `lodash-es` is bundled.
81
+ `msw` v2 is a peer dependency, and `@jest/types` is an optional peer that only TypeScript consumers of `jest-config` need. `babel-jest` is an optional peer too. The `.mjs` transform names it as a bare string, so Jest resolves it from your `rootDir`, and you need it installed there. `@whatwg-node/fetch` is the only regular dependency; `lodash-es` is bundled.
82
+
83
+ ### Wait budgets
84
+
85
+ `setupBeforeEach` gives booting the app a longer wait budget than the rest of the spec, without a flag threaded through helpers. Call `installSetupBudget` from a `setupFilesAfterEnv` file:
86
+
87
+ ```js
88
+ import { installSetupBudget } from '@gitlab/frontend-tests/integration/setup-budget';
89
+
90
+ installSetupBudget({ timeout: 3000 });
91
+ ```
92
+
93
+ Both options are optional:
94
+
95
+ - `timeout`: ceiling for regular waits. Defaults to 3000.
96
+ - `setupTimeout`: ceiling for waits inside `setupBeforeEach`. Defaults to 15000 in CI and 6000 locally. It must stay under the `testTimeout` that `createFrontendIntegrationConfig` sets (20000 in CI, 7000 locally), or `installSetupBudget` throws. A consumer that overrides `testTimeout` is not checked.
97
+
98
+ `installSetupBudget` installs a `@testing-library/dom` `asyncWrapper` and exposes `setupBeforeEach` as a global. `setupBeforeEach(fn)` registers a regular `beforeEach`. Every wait that runs while `fn` runs, including waits inside helpers it calls, gets `setupTimeout`. Every other wait gets `timeout`. Hooks run in declaration order, so a `beforeEach` declared above `setupBeforeEach` in the same block runs on `timeout`. An explicit `timeout` passed to a wait still wins, but the slow-wait log measures it against the budget. `installSetupBudget` chains to an `asyncWrapper` installed before it. TypeScript specs get the `setupBeforeEach` global type from the import of `installSetupBudget`.
99
+
100
+ ```js
101
+ describe('when the item has labels', () => {
102
+ setupBeforeEach(async () => {
103
+ mountApp();
104
+ await waitForElement(findList);
105
+ });
106
+
107
+ describe('when a label is removed', () => {
108
+ beforeEach(() => removeLabel()); // regular budget
109
+
110
+ it('updates the list', async () => {
111
+ await waitForElement(findEmptyState); // regular budget
112
+ });
113
+ });
114
+ });
115
+ ```
116
+
117
+ A wait that uses two thirds of its allowed run time is logged with `console.log` as `[integration] slow wait` or `[integration] slow setup wait`. When `JEST_INTEGRATION_SLOW_WAITS_FILE` is set, each slow wait is also appended to that file as one JSON line: `{ file, test, elapsedMs, ceilingMs, phase }`, where `phase` is `setup` or `test` (`WAIT_PHASE`).
118
+
119
+ `@gitlab/frontend-tests/integration/setup-budget-lint` exports `SETUP_BUDGET_RESTRICTED_SYNTAX` and `SETUP_BUDGET_GLOBALS` for ESLint flat config. ESLint keeps one `no-restricted-syntax` setting per file match, so spread the entries into the existing list:
120
+
121
+ ```js
122
+ import {
123
+ SETUP_BUDGET_GLOBALS,
124
+ SETUP_BUDGET_RESTRICTED_SYNTAX,
125
+ } from '@gitlab/frontend-tests/integration/setup-budget-lint';
126
+
127
+ export default [
128
+ {
129
+ files: ['spec/integration/**/*_spec.js'],
130
+ languageOptions: { globals: SETUP_BUDGET_GLOBALS },
131
+ rules: { 'no-restricted-syntax': ['error', ...SETUP_BUDGET_RESTRICTED_SYNTAX] },
132
+ },
133
+ ];
134
+ ```
135
+
136
+ The rules:
137
+
138
+ - Each test gets at most one `setupBeforeEach`. A `setupBeforeEach` inside a `describe` that already has one higher up is an error, and so are two in the same block.
139
+ - Waits do not set their own `timeout`. If a wait really cannot be faster, disable the rule on that line and say why.
140
+
141
+ The lint entries live in their own subpath so an ESLint config does not load the test runtime.
142
+
143
+ `@testing-library/dom` is an optional peer dependency that only `setup-budget` needs. The budget is not exported from `@gitlab/frontend-tests/integration`, so consumers that only use fixtures and the server do not need it.
79
144
 
80
145
  ### Gotchas
81
146
 
@@ -2,6 +2,49 @@
2
2
 
3
3
  // `msw` dependencies that ship ESM only, so Jest has to transform them.
4
4
  const MSW_ESM_DEPENDENCIES = ['rettime', 'until-async', '@open-draft/.*'];
5
+ // Integration specs run real Apollo. `@vue/apollo-composable` imports `@apollo/client`'s
6
+ // ESM files by path, and those import the ESM-only entry of `ts-invariant`.
7
+ const APOLLO_ESM_DEPENDENCIES = [
8
+ '@apollo/client',
9
+ '@vue/apollo-composable',
10
+ 'ts-invariant',
11
+ ];
12
+ const INTEGRATION_ESM_DEPENDENCIES = [...MSW_ESM_DEPENDENCIES, ...APOLLO_ESM_DEPENDENCIES];
13
+ // The two shapes of `transformIgnorePatterns` entry the factory knows how to extend:
14
+ // the pnpm layout, where packages live at `node_modules/.pnpm/<name>@<version>/`, and
15
+ // the flat layout of npm and Yarn (`node_modules/<name>/`, Yarn PnP paths included).
16
+ const PNPM_ALLOWLIST_MARKER = 'node_modules/\\.pnpm/(?!(';
17
+ const FLAT_ALLOWLIST_MARKER = 'node_modules/(?!(';
18
+ // pnpm stores `@scope/name` as `@scope+name`.
19
+ const toPnpmName = (name) => name.replace('/', '\\+');
20
+ // The pnpm store path of a dependency, for a flat allowlist whose group closes with `/`,
21
+ // so pnpm consumers with a flat pattern still match. `@[^/]*` swallows the version and
22
+ // any peer suffix (`@3.9.0_graphql@16.0.0`).
23
+ const toPnpmStorePath = (name) => `\\.pnpm/${toPnpmName(name)}@[^/]*`;
24
+ // Each allowlist shape the factory can extend, with the names it adds to it. In the pnpm
25
+ // shape the consumer's group already closes on the `@` before the version.
26
+ const ALLOWLIST_SHAPES = [
27
+ { marker: PNPM_ALLOWLIST_MARKER, names: INTEGRATION_ESM_DEPENDENCIES.map(toPnpmName) },
28
+ {
29
+ marker: FLAT_ALLOWLIST_MARKER,
30
+ names: INTEGRATION_ESM_DEPENDENCIES.flatMap((name) => [name, toPnpmStorePath(name)]),
31
+ },
32
+ ];
33
+ const findShape = (pattern) => ALLOWLIST_SHAPES.find(({ marker }) => pattern.includes(marker));
34
+ /**
35
+ * Adds the ESM-only dependencies to the allowlist of one `transformIgnorePatterns`
36
+ * entry. Returns the entry unchanged when it has neither known allowlist shape.
37
+ */
38
+ function allowEsmDependencies(pattern) {
39
+ const shape = findShape(pattern);
40
+ if (!shape)
41
+ return pattern;
42
+ return pattern.replace(shape.marker, () => `${shape.marker}${shape.names.join('|')}|`);
43
+ }
44
+ // Jest drops its default transform as soon as `transform` has any key.
45
+ const DEFAULT_SCRIPT_TRANSFORM_KEY = '\\.[jt]sx?$';
46
+ const MJS_TRANSFORM_KEY = '^.+\\.mjs$';
47
+ const integrationTestTimeout = () => (process.env.CI ? 20000 : 7000);
5
48
  // Order matters: `@whatwg-node/fetch` needs TextEncoder/TextDecoder at load time.
6
49
  const POLYFILLS_SETUP_FILES = [
7
50
  '@gitlab/frontend-tests/integration/polyfills/text-encoding',
@@ -9,23 +52,47 @@ const POLYFILLS_SETUP_FILES = [
9
52
  ];
10
53
  /**
11
54
  * Turns a consumer's Jest config into one that can run MSW integration specs. It
12
- * lets Jest transform the ESM-only MSW dependencies, loads the polyfills MSW needs
55
+ * lets Jest transform the ESM-only MSW and Apollo dependencies (in pnpm and flat
56
+ * npm/Yarn layouts), transforms `.mjs` files with `babel-jest`, loads the polyfills MSW needs
13
57
  * before anything else, keeps real timers and gives the specs a longer timeout.
14
58
  * Module aliases, the test environment and `setupFilesAfterEnv` stay the
15
59
  * consumer's responsibility.
60
+ *
61
+ * The consumer's `transformIgnorePatterns` must contain an allowlist of the shape
62
+ * `node_modules/\\.pnpm/(?!(a|b)@)` or `node_modules/(?!(a|b)/)`, otherwise this
63
+ * throws: a pattern without one can't be extended, and the specs would fail later
64
+ * on untransformed ESM. A `transform` entry for `.mjs` files wins over the default.
65
+ * `babel-jest` is resolved from the consumer's `rootDir`, so the consumer needs it.
16
66
  */
17
67
  function createFrontendIntegrationConfig(config = {}) {
18
- const { transformIgnorePatterns = [], setupFiles = [] } = config;
68
+ const { transformIgnorePatterns = [], setupFiles = [], transform } = config;
69
+ if (transformIgnorePatterns.length > 0 && !transformIgnorePatterns.some(findShape)) {
70
+ throw new Error([
71
+ 'createFrontendIntegrationConfig: no transformIgnorePatterns entry has an allowlist,',
72
+ 'so the ESM-only msw and Apollo dependencies would not be transformed.',
73
+ 'Add one of these to transformIgnorePatterns, with your own ESM-only packages in the group:',
74
+ ` pnpm: '${PNPM_ALLOWLIST_MARKER}your-package)@)'`,
75
+ ` npm/Yarn: '${FLAT_ALLOWLIST_MARKER}your-package)/)'`,
76
+ `Got: ${JSON.stringify(transformIgnorePatterns)}`,
77
+ ].join('\n'));
78
+ }
19
79
  return {
20
80
  ...config,
21
- transformIgnorePatterns: transformIgnorePatterns.map((pattern) => pattern.replace('node_modules/(?!(', `node_modules/(?!(${MSW_ESM_DEPENDENCIES.join('|')}|`)),
81
+ transformIgnorePatterns: transformIgnorePatterns.map(allowEsmDependencies),
82
+ transform: {
83
+ ...(transform === undefined && { [DEFAULT_SCRIPT_TRANSFORM_KEY]: 'babel-jest' }),
84
+ ...transform,
85
+ [MJS_TRANSFORM_KEY]: transform?.[MJS_TRANSFORM_KEY] ?? 'babel-jest',
86
+ },
22
87
  testPathIgnorePatterns: [],
23
88
  setupFiles: [...setupFiles, ...POLYFILLS_SETUP_FILES],
24
89
  fakeTimers: { enableGlobally: false },
25
- testTimeout: process.env.CI ? 20000 : 7000,
90
+ testTimeout: integrationTestTimeout(),
26
91
  };
27
92
  }
28
93
 
94
+ exports.APOLLO_ESM_DEPENDENCIES = APOLLO_ESM_DEPENDENCIES;
29
95
  exports.MSW_ESM_DEPENDENCIES = MSW_ESM_DEPENDENCIES;
30
96
  exports.POLYFILLS_SETUP_FILES = POLYFILLS_SETUP_FILES;
31
97
  exports.createFrontendIntegrationConfig = createFrontendIntegrationConfig;
98
+ exports.integrationTestTimeout = integrationTestTimeout;
@@ -1,11 +1,22 @@
1
1
  import type { Config } from '@jest/types';
2
2
  export declare const MSW_ESM_DEPENDENCIES: string[];
3
+ export declare const APOLLO_ESM_DEPENDENCIES: string[];
4
+ export declare const integrationTestTimeout: () => 20000 | 7000;
3
5
  export declare const POLYFILLS_SETUP_FILES: string[];
6
+ type IntegrationConfig = Config.InitialOptions & Required<Pick<Config.InitialOptions, 'transformIgnorePatterns' | 'transform' | 'setupFiles'>>;
4
7
  /**
5
8
  * Turns a consumer's Jest config into one that can run MSW integration specs. It
6
- * lets Jest transform the ESM-only MSW dependencies, loads the polyfills MSW needs
9
+ * lets Jest transform the ESM-only MSW and Apollo dependencies (in pnpm and flat
10
+ * npm/Yarn layouts), transforms `.mjs` files with `babel-jest`, loads the polyfills MSW needs
7
11
  * before anything else, keeps real timers and gives the specs a longer timeout.
8
12
  * Module aliases, the test environment and `setupFilesAfterEnv` stay the
9
13
  * consumer's responsibility.
14
+ *
15
+ * The consumer's `transformIgnorePatterns` must contain an allowlist of the shape
16
+ * `node_modules/\\.pnpm/(?!(a|b)@)` or `node_modules/(?!(a|b)/)`, otherwise this
17
+ * throws: a pattern without one can't be extended, and the specs would fail later
18
+ * on untransformed ESM. A `transform` entry for `.mjs` files wins over the default.
19
+ * `babel-jest` is resolved from the consumer's `rootDir`, so the consumer needs it.
10
20
  */
11
- export declare function createFrontendIntegrationConfig(config?: Config.InitialOptions): Config.InitialOptions;
21
+ export declare function createFrontendIntegrationConfig(config?: Config.InitialOptions): IntegrationConfig;
22
+ export {};
@@ -1,11 +1,22 @@
1
1
  import type { Config } from '@jest/types';
2
2
  export declare const MSW_ESM_DEPENDENCIES: string[];
3
+ export declare const APOLLO_ESM_DEPENDENCIES: string[];
4
+ export declare const integrationTestTimeout: () => 20000 | 7000;
3
5
  export declare const POLYFILLS_SETUP_FILES: string[];
6
+ type IntegrationConfig = Config.InitialOptions & Required<Pick<Config.InitialOptions, 'transformIgnorePatterns' | 'transform' | 'setupFiles'>>;
4
7
  /**
5
8
  * Turns a consumer's Jest config into one that can run MSW integration specs. It
6
- * lets Jest transform the ESM-only MSW dependencies, loads the polyfills MSW needs
9
+ * lets Jest transform the ESM-only MSW and Apollo dependencies (in pnpm and flat
10
+ * npm/Yarn layouts), transforms `.mjs` files with `babel-jest`, loads the polyfills MSW needs
7
11
  * before anything else, keeps real timers and gives the specs a longer timeout.
8
12
  * Module aliases, the test environment and `setupFilesAfterEnv` stay the
9
13
  * consumer's responsibility.
14
+ *
15
+ * The consumer's `transformIgnorePatterns` must contain an allowlist of the shape
16
+ * `node_modules/\\.pnpm/(?!(a|b)@)` or `node_modules/(?!(a|b)/)`, otherwise this
17
+ * throws: a pattern without one can't be extended, and the specs would fail later
18
+ * on untransformed ESM. A `transform` entry for `.mjs` files wins over the default.
19
+ * `babel-jest` is resolved from the consumer's `rootDir`, so the consumer needs it.
10
20
  */
11
- export declare function createFrontendIntegrationConfig(config?: Config.InitialOptions): Config.InitialOptions;
21
+ export declare function createFrontendIntegrationConfig(config?: Config.InitialOptions): IntegrationConfig;
22
+ export {};
@@ -1,5 +1,48 @@
1
1
  // `msw` dependencies that ship ESM only, so Jest has to transform them.
2
2
  const MSW_ESM_DEPENDENCIES = ['rettime', 'until-async', '@open-draft/.*'];
3
+ // Integration specs run real Apollo. `@vue/apollo-composable` imports `@apollo/client`'s
4
+ // ESM files by path, and those import the ESM-only entry of `ts-invariant`.
5
+ const APOLLO_ESM_DEPENDENCIES = [
6
+ '@apollo/client',
7
+ '@vue/apollo-composable',
8
+ 'ts-invariant',
9
+ ];
10
+ const INTEGRATION_ESM_DEPENDENCIES = [...MSW_ESM_DEPENDENCIES, ...APOLLO_ESM_DEPENDENCIES];
11
+ // The two shapes of `transformIgnorePatterns` entry the factory knows how to extend:
12
+ // the pnpm layout, where packages live at `node_modules/.pnpm/<name>@<version>/`, and
13
+ // the flat layout of npm and Yarn (`node_modules/<name>/`, Yarn PnP paths included).
14
+ const PNPM_ALLOWLIST_MARKER = 'node_modules/\\.pnpm/(?!(';
15
+ const FLAT_ALLOWLIST_MARKER = 'node_modules/(?!(';
16
+ // pnpm stores `@scope/name` as `@scope+name`.
17
+ const toPnpmName = (name) => name.replace('/', '\\+');
18
+ // The pnpm store path of a dependency, for a flat allowlist whose group closes with `/`,
19
+ // so pnpm consumers with a flat pattern still match. `@[^/]*` swallows the version and
20
+ // any peer suffix (`@3.9.0_graphql@16.0.0`).
21
+ const toPnpmStorePath = (name) => `\\.pnpm/${toPnpmName(name)}@[^/]*`;
22
+ // Each allowlist shape the factory can extend, with the names it adds to it. In the pnpm
23
+ // shape the consumer's group already closes on the `@` before the version.
24
+ const ALLOWLIST_SHAPES = [
25
+ { marker: PNPM_ALLOWLIST_MARKER, names: INTEGRATION_ESM_DEPENDENCIES.map(toPnpmName) },
26
+ {
27
+ marker: FLAT_ALLOWLIST_MARKER,
28
+ names: INTEGRATION_ESM_DEPENDENCIES.flatMap((name) => [name, toPnpmStorePath(name)]),
29
+ },
30
+ ];
31
+ const findShape = (pattern) => ALLOWLIST_SHAPES.find(({ marker }) => pattern.includes(marker));
32
+ /**
33
+ * Adds the ESM-only dependencies to the allowlist of one `transformIgnorePatterns`
34
+ * entry. Returns the entry unchanged when it has neither known allowlist shape.
35
+ */
36
+ function allowEsmDependencies(pattern) {
37
+ const shape = findShape(pattern);
38
+ if (!shape)
39
+ return pattern;
40
+ return pattern.replace(shape.marker, () => `${shape.marker}${shape.names.join('|')}|`);
41
+ }
42
+ // Jest drops its default transform as soon as `transform` has any key.
43
+ const DEFAULT_SCRIPT_TRANSFORM_KEY = '\\.[jt]sx?$';
44
+ const MJS_TRANSFORM_KEY = '^.+\\.mjs$';
45
+ const integrationTestTimeout = () => (process.env.CI ? 20000 : 7000);
3
46
  // Order matters: `@whatwg-node/fetch` needs TextEncoder/TextDecoder at load time.
4
47
  const POLYFILLS_SETUP_FILES = [
5
48
  '@gitlab/frontend-tests/integration/polyfills/text-encoding',
@@ -7,21 +50,43 @@ const POLYFILLS_SETUP_FILES = [
7
50
  ];
8
51
  /**
9
52
  * Turns a consumer's Jest config into one that can run MSW integration specs. It
10
- * lets Jest transform the ESM-only MSW dependencies, loads the polyfills MSW needs
53
+ * lets Jest transform the ESM-only MSW and Apollo dependencies (in pnpm and flat
54
+ * npm/Yarn layouts), transforms `.mjs` files with `babel-jest`, loads the polyfills MSW needs
11
55
  * before anything else, keeps real timers and gives the specs a longer timeout.
12
56
  * Module aliases, the test environment and `setupFilesAfterEnv` stay the
13
57
  * consumer's responsibility.
58
+ *
59
+ * The consumer's `transformIgnorePatterns` must contain an allowlist of the shape
60
+ * `node_modules/\\.pnpm/(?!(a|b)@)` or `node_modules/(?!(a|b)/)`, otherwise this
61
+ * throws: a pattern without one can't be extended, and the specs would fail later
62
+ * on untransformed ESM. A `transform` entry for `.mjs` files wins over the default.
63
+ * `babel-jest` is resolved from the consumer's `rootDir`, so the consumer needs it.
14
64
  */
15
65
  function createFrontendIntegrationConfig(config = {}) {
16
- const { transformIgnorePatterns = [], setupFiles = [] } = config;
66
+ const { transformIgnorePatterns = [], setupFiles = [], transform } = config;
67
+ if (transformIgnorePatterns.length > 0 && !transformIgnorePatterns.some(findShape)) {
68
+ throw new Error([
69
+ 'createFrontendIntegrationConfig: no transformIgnorePatterns entry has an allowlist,',
70
+ 'so the ESM-only msw and Apollo dependencies would not be transformed.',
71
+ 'Add one of these to transformIgnorePatterns, with your own ESM-only packages in the group:',
72
+ ` pnpm: '${PNPM_ALLOWLIST_MARKER}your-package)@)'`,
73
+ ` npm/Yarn: '${FLAT_ALLOWLIST_MARKER}your-package)/)'`,
74
+ `Got: ${JSON.stringify(transformIgnorePatterns)}`,
75
+ ].join('\n'));
76
+ }
17
77
  return {
18
78
  ...config,
19
- transformIgnorePatterns: transformIgnorePatterns.map((pattern) => pattern.replace('node_modules/(?!(', `node_modules/(?!(${MSW_ESM_DEPENDENCIES.join('|')}|`)),
79
+ transformIgnorePatterns: transformIgnorePatterns.map(allowEsmDependencies),
80
+ transform: {
81
+ ...(transform === undefined && { [DEFAULT_SCRIPT_TRANSFORM_KEY]: 'babel-jest' }),
82
+ ...transform,
83
+ [MJS_TRANSFORM_KEY]: transform?.[MJS_TRANSFORM_KEY] ?? 'babel-jest',
84
+ },
20
85
  testPathIgnorePatterns: [],
21
86
  setupFiles: [...setupFiles, ...POLYFILLS_SETUP_FILES],
22
87
  fakeTimers: { enableGlobally: false },
23
- testTimeout: process.env.CI ? 20000 : 7000,
88
+ testTimeout: integrationTestTimeout(),
24
89
  };
25
90
  }
26
91
 
27
- export { MSW_ESM_DEPENDENCIES, POLYFILLS_SETUP_FILES, createFrontendIntegrationConfig };
92
+ export { APOLLO_ESM_DEPENDENCIES, MSW_ESM_DEPENDENCIES, POLYFILLS_SETUP_FILES, createFrontendIntegrationConfig, integrationTestTimeout };
@@ -0,0 +1,88 @@
1
+ 'use strict';
2
+
3
+ var node_fs = require('node:fs');
4
+ var dom = require('@testing-library/dom');
5
+ var integration_jest_config = require('./jest_config.cjs');
6
+
7
+ /** The `phase` of a slow wait in the log and the slow-waits file. */
8
+ const WAIT_PHASE = { SETUP: 'setup', TEST: 'test' };
9
+ // A wait that uses this share of its ceiling passes locally and flakes on a starved CI runner.
10
+ const SLOW_SHARE = 2 / 3;
11
+ let budget = { timeout: 3000, setupTimeout: process.env.CI ? 15000 : 6000 };
12
+ let settingUp = false;
13
+ let innerWrapper = (cb) => cb();
14
+ /**
15
+ * A `beforeEach` whose waits, including those inside helpers it awaits, get the setup
16
+ * budget. Use it once per test path, to boot the app. Hooks run in declaration order, so
17
+ * a `beforeEach` declared above it in the same block runs on the regular budget.
18
+ */
19
+ function setupBeforeEach(fn, hookTimeout) {
20
+ beforeEach(async () => {
21
+ settingUp = true;
22
+ try {
23
+ await fn();
24
+ }
25
+ finally {
26
+ settingUp = false;
27
+ }
28
+ }, hookTimeout);
29
+ }
30
+ function logSlowWait(elapsedMs, ceilingMs, phase) {
31
+ const { testPath, currentTestName } = expect.getState();
32
+ const isSetup = phase === WAIT_PHASE.SETUP;
33
+ const advice = isSetup
34
+ ? 'Setup is close to its budget; find what makes it slow.'
35
+ : 'Move the setup into setupBeforeEach, or split the wait.';
36
+ // `console.log`, not `warn`: consumers' console watchers often turn `warn` into a failure.
37
+ // eslint-disable-next-line no-console
38
+ console.log(`[integration] slow ${isSetup ? 'setup ' : ''}wait: ${elapsedMs}ms in "${currentTestName}" (ceiling ${ceilingMs}ms). ${advice}`);
39
+ // One JSON line per wait, so a reporter can list them; appends stay atomic across workers.
40
+ if (process.env.JEST_INTEGRATION_SLOW_WAITS_FILE) {
41
+ node_fs.appendFileSync(process.env.JEST_INTEGRATION_SLOW_WAITS_FILE, `${JSON.stringify({ file: testPath, test: currentTestName, elapsedMs, ceilingMs, phase })}\n`);
42
+ }
43
+ }
44
+ // Installed as @testing-library's `asyncWrapper`. `waitFor` reads `asyncUtilTimeout` inside
45
+ // it, so setting the timeout here picks the budget for each wait.
46
+ async function setupBudgetAsyncWrapper(callback) {
47
+ const phase = settingUp ? WAIT_PHASE.SETUP : WAIT_PHASE.TEST;
48
+ const ceilingMs = settingUp ? budget.setupTimeout : budget.timeout;
49
+ dom.configure({ asyncUtilTimeout: ceilingMs });
50
+ const start = performance.now();
51
+ try {
52
+ return (await innerWrapper(callback));
53
+ }
54
+ finally {
55
+ // ponytail: an explicit `timeout` on the wait is invisible here, so it is logged against the budget.
56
+ const elapsedMs = Math.round(performance.now() - start);
57
+ if (elapsedMs > ceilingMs * SLOW_SHARE)
58
+ logSlowWait(elapsedMs, ceilingMs, phase);
59
+ }
60
+ }
61
+ /**
62
+ * Call from a `setupFilesAfterEnv` file. Sets the wait budgets, installs the wrapper and
63
+ * exposes `setupBeforeEach` as a global.
64
+ */
65
+ function installSetupBudget(options = {}) {
66
+ const next = {
67
+ timeout: options.timeout ?? budget.timeout,
68
+ setupTimeout: options.setupTimeout ?? budget.setupTimeout,
69
+ };
70
+ // Compares with the `testTimeout` from `createFrontendIntegrationConfig`. A consumer that
71
+ // sets its own `testTimeout` after the factory is not checked.
72
+ const hookTimeout = integration_jest_config.integrationTestTimeout();
73
+ if (next.setupTimeout >= hookTimeout) {
74
+ throw new Error(`setupTimeout (${next.setupTimeout}ms) must stay under the hook timeout (${hookTimeout}ms).`);
75
+ }
76
+ budget = next;
77
+ // Chain to a wrapper the consumer installed earlier, such as an `act()` wrapper.
78
+ const { asyncWrapper } = dom.getConfig();
79
+ if (asyncWrapper !== setupBudgetAsyncWrapper)
80
+ innerWrapper = asyncWrapper;
81
+ dom.configure({ asyncUtilTimeout: budget.timeout, asyncWrapper: setupBudgetAsyncWrapper });
82
+ Object.assign(globalThis, { setupBeforeEach });
83
+ }
84
+
85
+ exports.WAIT_PHASE = WAIT_PHASE;
86
+ exports.installSetupBudget = installSetupBudget;
87
+ exports.setupBeforeEach = setupBeforeEach;
88
+ exports.setupBudgetAsyncWrapper = setupBudgetAsyncWrapper;
@@ -0,0 +1,28 @@
1
+ export interface SetupBudgetOptions {
2
+ /** Ceiling for waits outside `setupBeforeEach`. */
3
+ timeout?: number;
4
+ /** Ceiling for waits inside `setupBeforeEach`. Must stay under the hook timeout. */
5
+ setupTimeout?: number;
6
+ }
7
+ type Hook = () => unknown;
8
+ /** The `phase` of a slow wait in the log and the slow-waits file. */
9
+ export declare const WAIT_PHASE: {
10
+ readonly SETUP: "setup";
11
+ readonly TEST: "test";
12
+ };
13
+ declare global {
14
+ var setupBeforeEach: (fn: Hook, hookTimeout?: number) => void;
15
+ }
16
+ /**
17
+ * A `beforeEach` whose waits, including those inside helpers it awaits, get the setup
18
+ * budget. Use it once per test path, to boot the app. Hooks run in declaration order, so
19
+ * a `beforeEach` declared above it in the same block runs on the regular budget.
20
+ */
21
+ export declare function setupBeforeEach(fn: Hook, hookTimeout?: number): void;
22
+ export declare function setupBudgetAsyncWrapper<T>(callback: () => Promise<T>): Promise<T>;
23
+ /**
24
+ * Call from a `setupFilesAfterEnv` file. Sets the wait budgets, installs the wrapper and
25
+ * exposes `setupBeforeEach` as a global.
26
+ */
27
+ export declare function installSetupBudget(options?: SetupBudgetOptions): void;
28
+ export {};
@@ -0,0 +1,28 @@
1
+ export interface SetupBudgetOptions {
2
+ /** Ceiling for waits outside `setupBeforeEach`. */
3
+ timeout?: number;
4
+ /** Ceiling for waits inside `setupBeforeEach`. Must stay under the hook timeout. */
5
+ setupTimeout?: number;
6
+ }
7
+ type Hook = () => unknown;
8
+ /** The `phase` of a slow wait in the log and the slow-waits file. */
9
+ export declare const WAIT_PHASE: {
10
+ readonly SETUP: "setup";
11
+ readonly TEST: "test";
12
+ };
13
+ declare global {
14
+ var setupBeforeEach: (fn: Hook, hookTimeout?: number) => void;
15
+ }
16
+ /**
17
+ * A `beforeEach` whose waits, including those inside helpers it awaits, get the setup
18
+ * budget. Use it once per test path, to boot the app. Hooks run in declaration order, so
19
+ * a `beforeEach` declared above it in the same block runs on the regular budget.
20
+ */
21
+ export declare function setupBeforeEach(fn: Hook, hookTimeout?: number): void;
22
+ export declare function setupBudgetAsyncWrapper<T>(callback: () => Promise<T>): Promise<T>;
23
+ /**
24
+ * Call from a `setupFilesAfterEnv` file. Sets the wait budgets, installs the wrapper and
25
+ * exposes `setupBeforeEach` as a global.
26
+ */
27
+ export declare function installSetupBudget(options?: SetupBudgetOptions): void;
28
+ export {};
@@ -0,0 +1,83 @@
1
+ import { appendFileSync } from 'node:fs';
2
+ import { getConfig, configure } from '@testing-library/dom';
3
+ import { integrationTestTimeout } from './jest_config.js';
4
+
5
+ /** The `phase` of a slow wait in the log and the slow-waits file. */
6
+ const WAIT_PHASE = { SETUP: 'setup', TEST: 'test' };
7
+ // A wait that uses this share of its ceiling passes locally and flakes on a starved CI runner.
8
+ const SLOW_SHARE = 2 / 3;
9
+ let budget = { timeout: 3000, setupTimeout: process.env.CI ? 15000 : 6000 };
10
+ let settingUp = false;
11
+ let innerWrapper = (cb) => cb();
12
+ /**
13
+ * A `beforeEach` whose waits, including those inside helpers it awaits, get the setup
14
+ * budget. Use it once per test path, to boot the app. Hooks run in declaration order, so
15
+ * a `beforeEach` declared above it in the same block runs on the regular budget.
16
+ */
17
+ function setupBeforeEach(fn, hookTimeout) {
18
+ beforeEach(async () => {
19
+ settingUp = true;
20
+ try {
21
+ await fn();
22
+ }
23
+ finally {
24
+ settingUp = false;
25
+ }
26
+ }, hookTimeout);
27
+ }
28
+ function logSlowWait(elapsedMs, ceilingMs, phase) {
29
+ const { testPath, currentTestName } = expect.getState();
30
+ const isSetup = phase === WAIT_PHASE.SETUP;
31
+ const advice = isSetup
32
+ ? 'Setup is close to its budget; find what makes it slow.'
33
+ : 'Move the setup into setupBeforeEach, or split the wait.';
34
+ // `console.log`, not `warn`: consumers' console watchers often turn `warn` into a failure.
35
+ // eslint-disable-next-line no-console
36
+ console.log(`[integration] slow ${isSetup ? 'setup ' : ''}wait: ${elapsedMs}ms in "${currentTestName}" (ceiling ${ceilingMs}ms). ${advice}`);
37
+ // One JSON line per wait, so a reporter can list them; appends stay atomic across workers.
38
+ if (process.env.JEST_INTEGRATION_SLOW_WAITS_FILE) {
39
+ appendFileSync(process.env.JEST_INTEGRATION_SLOW_WAITS_FILE, `${JSON.stringify({ file: testPath, test: currentTestName, elapsedMs, ceilingMs, phase })}\n`);
40
+ }
41
+ }
42
+ // Installed as @testing-library's `asyncWrapper`. `waitFor` reads `asyncUtilTimeout` inside
43
+ // it, so setting the timeout here picks the budget for each wait.
44
+ async function setupBudgetAsyncWrapper(callback) {
45
+ const phase = settingUp ? WAIT_PHASE.SETUP : WAIT_PHASE.TEST;
46
+ const ceilingMs = settingUp ? budget.setupTimeout : budget.timeout;
47
+ configure({ asyncUtilTimeout: ceilingMs });
48
+ const start = performance.now();
49
+ try {
50
+ return (await innerWrapper(callback));
51
+ }
52
+ finally {
53
+ // ponytail: an explicit `timeout` on the wait is invisible here, so it is logged against the budget.
54
+ const elapsedMs = Math.round(performance.now() - start);
55
+ if (elapsedMs > ceilingMs * SLOW_SHARE)
56
+ logSlowWait(elapsedMs, ceilingMs, phase);
57
+ }
58
+ }
59
+ /**
60
+ * Call from a `setupFilesAfterEnv` file. Sets the wait budgets, installs the wrapper and
61
+ * exposes `setupBeforeEach` as a global.
62
+ */
63
+ function installSetupBudget(options = {}) {
64
+ const next = {
65
+ timeout: options.timeout ?? budget.timeout,
66
+ setupTimeout: options.setupTimeout ?? budget.setupTimeout,
67
+ };
68
+ // Compares with the `testTimeout` from `createFrontendIntegrationConfig`. A consumer that
69
+ // sets its own `testTimeout` after the factory is not checked.
70
+ const hookTimeout = integrationTestTimeout();
71
+ if (next.setupTimeout >= hookTimeout) {
72
+ throw new Error(`setupTimeout (${next.setupTimeout}ms) must stay under the hook timeout (${hookTimeout}ms).`);
73
+ }
74
+ budget = next;
75
+ // Chain to a wrapper the consumer installed earlier, such as an `act()` wrapper.
76
+ const { asyncWrapper } = getConfig();
77
+ if (asyncWrapper !== setupBudgetAsyncWrapper)
78
+ innerWrapper = asyncWrapper;
79
+ configure({ asyncUtilTimeout: budget.timeout, asyncWrapper: setupBudgetAsyncWrapper });
80
+ Object.assign(globalThis, { setupBeforeEach });
81
+ }
82
+
83
+ export { WAIT_PHASE, installSetupBudget, setupBeforeEach, setupBudgetAsyncWrapper };
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ // `no-restricted-syntax` entries for specs that use `setupBeforeEach`. ESLint keeps one
4
+ // `no-restricted-syntax` setting per file match, so consumers spread these into theirs.
5
+ const NAME = '/^[fx]?describe$/';
6
+ // `describe(...)`, `describe.only(...)`, `describe.each(table)(...)` and describe.each`table`(...).
7
+ const DESCRIBE = `:matches(CallExpression[callee.name=${NAME}], CallExpression[callee.object.name=${NAME}], CallExpression[callee.callee.object.name=${NAME}], CallExpression[callee.tag.object.name=${NAME}])`;
8
+ const SETUP = "CallExpression[callee.name='setupBeforeEach']";
9
+ const SETUP_STATEMENT = `ExpressionStatement:has(> ${SETUP})`;
10
+ const SETUP_BUDGET_RESTRICTED_SYNTAX = [
11
+ {
12
+ // Each test boots on the setup budget once: no setupBeforeEach below another one.
13
+ selector: `:matches(Program, BlockStatement):has(> ${SETUP_STATEMENT}) ${DESCRIBE} ${SETUP}`,
14
+ message: 'A setupBeforeEach higher up already boots these tests. Use beforeEach here; it gets the regular wait budget.',
15
+ },
16
+ {
17
+ selector: `${SETUP_STATEMENT} ~ ${SETUP_STATEMENT}`,
18
+ message: 'Use setupBeforeEach once per block. Put all setup in it.',
19
+ },
20
+ {
21
+ selector: "CallExpression:matches([callee.name=/^(waitFor|findBy|findAllBy)/], [callee.property.name=/^(findBy|findAllBy)/]) > ObjectExpression > Property[key.name='timeout']",
22
+ message: 'Find out why this wait is slow first; most slow waits are avoidable. If it is not, disable this line with a reason.',
23
+ },
24
+ ];
25
+ const SETUP_BUDGET_GLOBALS = { setupBeforeEach: 'readonly' };
26
+
27
+ exports.SETUP_BUDGET_GLOBALS = SETUP_BUDGET_GLOBALS;
28
+ exports.SETUP_BUDGET_RESTRICTED_SYNTAX = SETUP_BUDGET_RESTRICTED_SYNTAX;
@@ -0,0 +1,7 @@
1
+ export declare const SETUP_BUDGET_RESTRICTED_SYNTAX: {
2
+ selector: string;
3
+ message: string;
4
+ }[];
5
+ export declare const SETUP_BUDGET_GLOBALS: {
6
+ readonly setupBeforeEach: "readonly";
7
+ };
@@ -0,0 +1,7 @@
1
+ export declare const SETUP_BUDGET_RESTRICTED_SYNTAX: {
2
+ selector: string;
3
+ message: string;
4
+ }[];
5
+ export declare const SETUP_BUDGET_GLOBALS: {
6
+ readonly setupBeforeEach: "readonly";
7
+ };
@@ -0,0 +1,25 @@
1
+ // `no-restricted-syntax` entries for specs that use `setupBeforeEach`. ESLint keeps one
2
+ // `no-restricted-syntax` setting per file match, so consumers spread these into theirs.
3
+ const NAME = '/^[fx]?describe$/';
4
+ // `describe(...)`, `describe.only(...)`, `describe.each(table)(...)` and describe.each`table`(...).
5
+ const DESCRIBE = `:matches(CallExpression[callee.name=${NAME}], CallExpression[callee.object.name=${NAME}], CallExpression[callee.callee.object.name=${NAME}], CallExpression[callee.tag.object.name=${NAME}])`;
6
+ const SETUP = "CallExpression[callee.name='setupBeforeEach']";
7
+ const SETUP_STATEMENT = `ExpressionStatement:has(> ${SETUP})`;
8
+ const SETUP_BUDGET_RESTRICTED_SYNTAX = [
9
+ {
10
+ // Each test boots on the setup budget once: no setupBeforeEach below another one.
11
+ selector: `:matches(Program, BlockStatement):has(> ${SETUP_STATEMENT}) ${DESCRIBE} ${SETUP}`,
12
+ message: 'A setupBeforeEach higher up already boots these tests. Use beforeEach here; it gets the regular wait budget.',
13
+ },
14
+ {
15
+ selector: `${SETUP_STATEMENT} ~ ${SETUP_STATEMENT}`,
16
+ message: 'Use setupBeforeEach once per block. Put all setup in it.',
17
+ },
18
+ {
19
+ selector: "CallExpression:matches([callee.name=/^(waitFor|findBy|findAllBy)/], [callee.property.name=/^(findBy|findAllBy)/]) > ObjectExpression > Property[key.name='timeout']",
20
+ message: 'Find out why this wait is slow first; most slow waits are avoidable. If it is not, disable this line with a reason.',
21
+ },
22
+ ];
23
+ const SETUP_BUDGET_GLOBALS = { setupBeforeEach: 'readonly' };
24
+
25
+ export { SETUP_BUDGET_GLOBALS, SETUP_BUDGET_RESTRICTED_SYNTAX };
@@ -0,0 +1,2 @@
1
+ // Resolver stub for tools that ignore `exports` (webpack 4). Node and Jest use `exports`.
2
+ export * from '../dist/integration/setup_budget_lint.js';
@@ -0,0 +1,2 @@
1
+ // Resolver stub for tools that ignore `exports` (webpack 4). Node and Jest use `exports`.
2
+ export * from '../dist/integration/setup_budget.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gitlab/frontend-tests",
3
- "version": "0.1.5",
3
+ "version": "0.3.0",
4
4
  "description": "Reusable test infrastructure for GitLab frontend packages",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -20,6 +20,12 @@
20
20
  ],
21
21
  "integration/polyfills/text-encoding": [
22
22
  "./dist/integration/polyfills_text_encoding.d.ts"
23
+ ],
24
+ "integration/setup-budget": [
25
+ "./dist/integration/setup_budget.d.ts"
26
+ ],
27
+ "integration/setup-budget-lint": [
28
+ "./dist/integration/setup_budget_lint.d.ts"
23
29
  ]
24
30
  }
25
31
  },
@@ -74,6 +80,26 @@
74
80
  "default": "./dist/integration/jest_config.cjs"
75
81
  }
76
82
  },
83
+ "./integration/setup-budget": {
84
+ "import": {
85
+ "types": "./dist/integration/setup_budget.d.ts",
86
+ "default": "./dist/integration/setup_budget.js"
87
+ },
88
+ "require": {
89
+ "types": "./dist/integration/setup_budget.d.cts",
90
+ "default": "./dist/integration/setup_budget.cjs"
91
+ }
92
+ },
93
+ "./integration/setup-budget-lint": {
94
+ "import": {
95
+ "types": "./dist/integration/setup_budget_lint.d.ts",
96
+ "default": "./dist/integration/setup_budget_lint.js"
97
+ },
98
+ "require": {
99
+ "types": "./dist/integration/setup_budget_lint.d.cts",
100
+ "default": "./dist/integration/setup_budget_lint.cjs"
101
+ }
102
+ },
77
103
  "./*": {
78
104
  "import": {
79
105
  "types": "./dist/*.d.ts",
@@ -95,11 +121,19 @@
95
121
  },
96
122
  "peerDependencies": {
97
123
  "@jest/types": ">=29",
124
+ "@testing-library/dom": ">=9",
125
+ "babel-jest": ">=29",
98
126
  "msw": "^2.0.0"
99
127
  },
100
128
  "peerDependenciesMeta": {
101
129
  "@jest/types": {
102
130
  "optional": true
131
+ },
132
+ "babel-jest": {
133
+ "optional": true
134
+ },
135
+ "@testing-library/dom": {
136
+ "optional": true
103
137
  }
104
138
  },
105
139
  "devDependencies": {
@@ -109,6 +143,7 @@
109
143
  "@rollup/plugin-node-resolve": "^16.0.3",
110
144
  "@rollup/plugin-typescript": "^12.3.0",
111
145
  "@rstest/core": "^0.12.5",
146
+ "@testing-library/dom": "^10.4.2",
112
147
  "@types/lodash-es": "^4.17.12",
113
148
  "@types/node": "^20",
114
149
  "eslint": "^9.0.0",