@gitlab/frontend-tests

中文文档
0.2.0发布于 2026/11/14MITTypeScriptESM + CJS构建来源已验证近 30 天下载 6.5万

Reusable test infrastructure for GitLab frontend packages

原始使用文档
文档目录10 节
  1. Installation
  2. Development
  3. Adding a module
  4. Integration test core
  5. Modules
  6. Jest configuration
  7. Wait budgets
  8. Gotchas
  9. Publishing
  10. One-time setup

@gitlab/frontend-tests

Reusable test infrastructure for GitLab-owned frontend packages. It includes a shared Jest configuration for unit tests and a frontend integration test setup factory. Each package can set up its test infrastructure without copying files or following many manual steps.

Installation

pnpm add -D @gitlab/frontend-tests

Development

The package is written in TypeScript and built with rollup. Tests use Rstest. Linting uses ESLint 9 with a flat config and typescript-eslint.

tsconfig.json is the editor and pnpm typecheck config and covers the tests. tsconfig.build.json extends it for rollup and excludes the tests so they stay out of dist/.

Relative imports in src/ carry a .js extension (./types.js), which TypeScript maps to the .ts source. The emitted .d.ts files keep those specifiers, which node16 module resolution requires. After rollup, scripts/emit_cjs_types.mjs copies every .d.ts to a .d.cts twin for the require export condition, so CommonJS TypeScript consumers resolve types too. lodash-es is bundled into dist/ because it ships ESM only; the only runtime dependency is @whatwg-node/fetch.

pnpm install      # install dependencies
pnpm test         # run tests
pnpm build        # build dist/ (ESM, CJS and .d.ts)
pnpm lint         # run ESLint
pnpm typecheck    # run tsc --noEmit

Adding a module

  1. Add the module under src/.
  2. Add tests next to it as *.test.ts.
  3. Re-export the public API from src/index.ts. Put data shapes that several modules share, or that consumers write themselves, in src/integration/types.ts. Keep a type that describes one function's parameters or return value next to that function. Do not export implementation details. Name generic parameters with a single letter (T, K, V) or descriptively with a Type suffix (DataType), never with a T prefix; ESLint enforces this.
  4. Add the new entry to the input map in rollup.config.js, to exports and typesVersions in package.json, and add a root resolver stub (see Gotchas). This publishes it as the subpath @gitlab/frontend-tests/<name>.

Integration test core

This package holds the framework core of GitLab's frontend integration tests. These tests mount a real Vue app in jsdom. They intercept GraphQL and REST requests at the network layer with Mock Service Worker (MSW). The core provides fixture loading, fixture variants, request capture and the MSW server wiring. It also provides a Jest config factory and the polyfills MSW needs.

Modules

@gitlab/frontend-tests/integration is the core. It exports:

  • Fixture utilities: loadFixturesMap(basePath), matchFixture, isValidGraphqlFixture, setFixtureData, setFixtureErrors, setFixtureItemsCount, createFixturePaginator. loadFixturesMap reads every *.json file in a directory and keys the results by camelCased operation name.
  • Fixture variants: defineFixtureVariants, defineRestFixtureVariants, setQueryVariant, activateVariant, getActiveVariant, getVariant, resetAllVariants, dumpRegistry.
  • Request capture: captureRequest, capturedRequests, resetCapturedRequests, snapshotRequests, expectGraphQLCalls, lastRequestVariables, captureMissingOperation, missingOperations, clearMissingOperations.
  • MSW wiring: buildHandlers(featureHandlers, restEndpoints) and createServer(featureHandlers, restEndpoints). buildHandlers creates one graphql.operation handler that tries each feature resolver in order. It also adds the REST endpoint handlers and a catch-all that answers 400. createServer builds an msw/node server from those handlers.
  • baseMetadata.
  • Types for consumers: GraphqlFixture, GraphqlFixtureInput, GraphqlVariables, FeatureHandler, RestEndpoint, RestFixture, FixtureVariants, CapturedRequest and RequestCounts. setQueryVariant derives its activator names from the variant keys, so setQueryVariant(constant).withError() is checked against the keys passed to defineFixtureVariants.

@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.

@gitlab/frontend-tests/integration/jest-config exports createFrontendIntegrationConfig(config) and MSW_ESM_DEPENDENCIES.

@gitlab/frontend-tests/integration/setup-budget and @gitlab/frontend-tests/integration/setup-budget-lint are described in Wait budgets.

Jest configuration

Pass an existing Jest config to the factory. It returns a copy with the integration overrides applied.

const { createFrontendIntegrationConfig } = require('@gitlab/frontend-tests/integration/jest-config');
const baseConfig = require('./jest.config.base');

module.exports = createFrontendIntegrationConfig({
  ...baseConfig,
  setupFilesAfterEnv: ['<rootDir>/spec/integration/test_setup.js'],
});

The factory changes these things:

  • Adds the ESM-only dependencies of msw (rettime, until-async, @open-draft/*) to the transformIgnorePatterns allowlist.
  • Appends the two polyfills entries to setupFiles, text encoding first.
  • Clears testPathIgnorePatterns.
  • Disables global fake timers.
  • Sets testTimeout to 20000 in CI and 7000 locally.

It does not touch setupFilesAfterEnv, module aliases or the test environment. Those stay with the consumer.

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.

Wait budgets

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:

import { installSetupBudget } from '@gitlab/frontend-tests/integration/setup-budget';

installSetupBudget({ timeout: 3000 });

Both options are optional:

  • timeout: ceiling for regular waits. Defaults to 3000.
  • 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.

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.

describe('when the item has labels', () => {
  setupBeforeEach(async () => {
    mountApp();
    await waitForElement(findList);
  });

  describe('when a label is removed', () => {
    beforeEach(() => removeLabel()); // regular budget

    it('updates the list', async () => {
      await waitForElement(findEmptyState); // regular budget
    });
  });
});

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).

@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:

import {
  SETUP_BUDGET_GLOBALS,
  SETUP_BUDGET_RESTRICTED_SYNTAX,
} from '@gitlab/frontend-tests/integration/setup-budget-lint';

export default [
  {
    files: ['spec/integration/**/*_spec.js'],
    languageOptions: { globals: SETUP_BUDGET_GLOBALS },
    rules: { 'no-restricted-syntax': ['error', ...SETUP_BUDGET_RESTRICTED_SYNTAX] },
  },
];

The rules:

  • 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.
  • Waits do not set their own timeout. If a wait really cannot be faster, disable the rule on that line and say why.

The lint entries live in their own subpath so an ESLint config does not load the test runtime.

@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.

Gotchas

  • Load the polyfills through setupFiles, not setupFilesAfterEnv. msw/node reads these globals while its module body evaluates, so they must exist before it loads. Keep the text-encoding entry before the main one: @whatwg-node/fetch needs TextDecoder at load time, and bundlers hoist imports, so a single file cannot guarantee the order.
  • The root-level integration.js and integration/*.js files are stubs for resolvers that ignore the exports field, such as webpack 4 and the ESLint import resolver built on it. Node and Jest never load them. Add one for every new subpath.
  • Make sure every import resolves to the same copy of this package. The variant registry and the captured-requests store are module-level singletons. With two copies, a variant activated in a spec is invisible to the handler.

Publishing

The package is published to the public npm registry (registry.npmjs.org), not the GitLab package registry. Only dist/ is published.

Publishing uses npm trusted publishing with OIDC. The publish job gets a short-lived ID token from GitLab CI (id_tokens, audience npm:registry.npmjs.org). No npm token is stored in CI variables. Packages are published with provenance attestations.

The publish job runs only on git tags that match v<digits>, for example v0.1.0. It runs after lint, typecheck, test and build pass.

To release:

  1. Merge your changes to main.
  2. Create and push a tag vX.Y.Z on main.

The tag pipeline publishes the package. The publish job sets version in package.json from the tag before publishing, so no version-bump merge request is needed. Releases do not update the committed version; the tag is authoritative. package.json carries the placeholder 0.0.0-development, which is never published. Do not bump it by hand. To check what is released, run npm view @gitlab/frontend-tests version, or look at the latest release on the project overview.

After publish succeeds, the release job creates a GitLab release for the tag, with a one-line description and a link to the npm package. It does not run if publish fails, so a release always means the version is on npm.

Tags must be vMAJOR.MINOR.PATCH, with an optional prerelease suffix (for example v1.0.0-rc.1), or the publish job fails. Stable versions are published with the latest dist-tag; prerelease versions (those containing -) use the next dist-tag so they do not replace the stable release for consumers installing without a version or tag.

One-time setup

This is required before the first CI publish. Someone with publish rights on the @gitlab npm organization must do it.

  1. Publish the first version by hand from a logged-in machine with npm publish --access public. The trusted publisher is set on an existing package's settings on npmjs.com, so the package must exist first.
  2. On npmjs.com, open the package Settings and find the Trusted Publisher section. Choose GitLab CI/CD and enter:
    • Namespace: gitlab-org/frontend/toolkit
    • Project name: tests
    • Top-level CI file path: .gitlab-ci.yml
    • Allow npm publish
  3. Optional: under Publishing access, choose "Require two-factor authentication and disallow tokens".

After this, tag pipelines publish on their own.

版本与发布记录

@gitlab/frontend-tests 共发布 9 个版本,首次发布于 2026/10/05;过去 12 个月发布了 9 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.0latest2026/11/142 天前
0.1.52026/11/079 天前
0.1.5-rc.1next2026/11/069 天前
0.1.5-rc.02026/11/069 天前
0.1.42026/10/2917 天前
0.1.32026/10/1730 天前

关于 @gitlab/frontend-tests 的常见问题

@gitlab/frontend-tests 是什么?

Reusable test infrastructure for GitLab frontend packages

如何安装 @gitlab/frontend-tests?

在项目目录运行 npm install @gitlab/frontend-tests,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:msw(^2.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gitlab/frontend-tests 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gitlab/frontend-tests 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gitlab/frontend-tests 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gitlab/frontend-tests 可以商用吗?

@gitlab/frontend-tests 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gitlab/frontend-tests 的下载量有多少?

根据 npm 官方下载统计,@gitlab/frontend-tests 在 2026/10/17 – 2026/11/15 这 30 天内被下载 65,244 次,日均约 2,175 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gitlab/frontend-tests 还在维护吗?

最新版本 0.2.0 发布于 2026/11/14(2 天前);至今共发布 9 个版本,其中过去 12 个月发布了 9 个;首次发布于 2026/10/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。