Skip to content
Tags
cypresse2e-testingapi-testingtest-generationcodegenopenapi
Details
  • Updated 2 days ago
  • Created 1 year ago
Official v5.0.0-beta.42 MIT kubb >=5.0.0 node >=22

@kubb/plugin-cypress

Generate typed `cy.request()` wrappers from OpenAPI so end-to-end tests reuse one source of truth for API calls.

Downloads
38.5k / mo
Stars
3
Bundle size
195.2 kB
Updated
2d ago

@kubb/plugin-cypress

Generate one typed cy.request() wrapper per OpenAPI operation. Each helper has typed path params, body, query, and a typed response — so failing API calls in Cypress show up at compile time instead of inside the test runner.

Use these helpers in before/beforeEach hooks to seed data, in custom commands, or in API-only test specs.

Installation

shell
bun add -d @kubb/plugin-cypress@beta
shell
pnpm add -D @kubb/plugin-cypress@beta
shell
npm install --save-dev @kubb/plugin-cypress@beta
shell
yarn add -D @kubb/plugin-cypress@beta

Options

output

Where the generated Cypress helpers are written and how they are exported.

Type: Output
Required: false
Default: { path: 'cypress', barrel: { type: 'named' } }

output.path

Folder (or single file) where the plugin writes its generated code. The path is resolved against the global output.path set on defineConfig.

Use a folder to keep each generator's output isolated ('types', 'clients', 'hooks'). Use a single file when you want everything in one place, for example 'api.ts'.

Type: string
Required: true
Default: 'cypress'

TIP

When output.path points to a single file, the group option cannot be used because every operation ends up in the same file.

typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      output: { path: './types' },
    }),
  ],
})
text
src/
└── gen/
    └── types/
        ├── Pet.ts
        └── Store.ts

output.barrel

Controls how the generated index.ts (barrel) file re-exports the plugin's output.

  • { type: 'named' } re-exports each symbol by name. Best for tree-shaking and explicit imports.
  • { type: 'all' } uses export *. Smaller barrel file, but exports everything.
  • { nested: true } creates a barrel in every subdirectory, so callers can import from any depth.
  • false skips the barrel entirely. The plugin's files are also excluded from the root index.ts.
Type: { type: 'named' | 'all', nested?: boolean } | false
Required: false
Default: { type: 'named' }

TIP

Pick 'named' when consumers care about which symbols they import (better tree-shaking, friendlier auto-import). Pick 'all' when the file count is small and you want a one-line barrel.

typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      output: { barrel: { type: 'named' } },
    }),
  ],
})
typescript
export { Pet, PetStatus } from './Pet'
export { Store } from './Store'
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      output: { barrel: { type: 'all' } },
    }),
  ],
})
typescript
export * from './Pet'
export * from './Store'
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      output: { barrel: { type: 'named', nested: true } },
    }),
  ],
})
text
src/gen/types/
├── index.ts          # re-exports ./petController and ./storeController
├── petController/
│   ├── index.ts      # re-exports Pet, Store, ...
│   └── Pet.ts
└── storeController/
    ├── index.ts
    └── Store.ts
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      output: { barrel: false },
    }),
  ],
})
text
# No index.ts is generated for this plugin.
# Its files are also excluded from the root index.ts.

output.banner

Text prepended to every generated file. Useful for license headers, lint disables, or @ts-nocheck directives.

Pass a string for a static banner. Pass a function to compute the banner from each file's RootNode (the AST root containing path, schema, and operation context).

Type: string | ((node: RootNode) => string)
Required: false
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      output: {
        banner: '/* eslint-disable */\n// @ts-nocheck',
      },
    }),
  ],
})
typescript
/* eslint-disable */
// @ts-nocheck
export type Pet = {
  id: number
  name: string
}
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      output: {
        banner: (node) => `// Source: ${node.path}\n// Generated at ${new Date().toISOString()}`,
      },
    }),
  ],
})

Text appended at the end of every generated file. The mirror of banner — use it for closing comments, re-enabling lint rules, or marker lines.

Pass a string for a static footer, or a function that receives the file's RootNode and returns the footer text.

Type: string | ((node: RootNode) => string)
Required: false
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      output: {
        banner: '/* eslint-disable */',
        footer: '/* eslint-enable */',
      },
    }),
  ],
})

output.override

Allows the plugin to overwrite hand-written files that share a name with a generated file.

  • false (default): Kubb skips a file if it already exists and is not marked as generated. This protects manual edits.
  • true: Kubb overwrites any file at the target path, including hand-written ones.
Type: boolean
Required: false
Default: false

WARNING

Enable this only when you are sure the target folder contains nothing you need to keep. Local edits are lost on the next generation.

typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      output: { override: true },
    }),
  ],
})

resolver

Overrides how the plugin builds names and paths for generated files and symbols. Use this to add prefixes, suffixes, or to swap the casing strategy without forking the plugin.

Only override the methods you want to change. Anything you omit falls back to the plugin's default resolver. A method that returns null or undefined also falls back.

Inside each method, this is bound to the full resolver, so you can call this.default(name, 'function') to delegate to the built-in implementation.

Type: Partial<ResolverCypress> & ThisType<ResolverCypress>
Required: false

TIP

Use resolver for naming and file-location tweaks. For changing the AST nodes themselves (e.g. stripping descriptions), use transformer instead.

Add an Api prefix to every name
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      resolver: {
        resolveName(name) {
          return `Api${this.default(name, 'function')}`
        },
      },
    }),
  ],
})

Each plugin ships with a default resolver:

Plugin Default resolver
@kubb/plugin-ts resolverTs
@kubb/plugin-zod resolverZod
@kubb/plugin-faker resolverFaker
@kubb/plugin-cypress resolverCypress
@kubb/plugin-msw resolverMsw
@kubb/plugin-mcp resolverMcp
@kubb/plugin-client resolverClient

paramsType

How operation parameters (path, query, headers) are exposed in the generated function signature.

  • 'inline' (default) — each parameter is a separate positional argument. Compact for operations with one or two params.
  • 'object' — every parameter is wrapped in a single object argument. Easier to read for operations with many params and named at the call site.
Type: 'object' | 'inline'
Required: false
Default: 'inline'

TIP

Setting paramsType: 'object' implicitly sets pathParamsType: 'object' as well, so call sites are consistent.

typescript
export async function deletePet(
  petId: DeletePetPathParams['petId'],
  headers?: DeletePetHeaderParams,
  config: Partial<RequestConfig> = {},
) {
  // ...
}
typescript
await deletePet(42)
typescript
export async function deletePet(
  {
    petId,
    headers,
  }: {
    petId: DeletePetPathParams['petId']
    headers?: DeletePetHeaderParams
  },
  config: Partial<RequestConfig> = {},
) {
  // ...
}
typescript
await deletePet({ petId: 42, headers: { 'X-Api-Key': 'secret' } })

paramsCasing

Renames path, query, and header parameters in the generated client to the chosen casing. The HTTP request still uses the original names from the OpenAPI spec — Kubb writes the mapping for you.

  • 'camelcase' — turn pet_id and X-Api-Key into petId and xApiKey in your TypeScript code. The runtime URL still uses /pet/{pet_id} and the header is still sent as X-Api-Key.
Type: 'camelcase'
Required: false

TIP

Callers write friendly camelCase names. The generated client maps them back to whatever the API expects (snake_case path params, kebab-case headers, ...).

IMPORTANT

Set the same paramsCasing on every plugin that touches operation parameters (@kubb/plugin-ts, @kubb/plugin-client, @kubb/plugin-react-query, @kubb/plugin-faker, @kubb/plugin-mcp). Mismatched casing causes type errors between generated layers.

typescript
// Function takes camelCase parameters
export async function deletePet(
  petId: DeletePetPathParams['petId'],
  headers?: DeletePetHeaderParams,
  config: Partial<RequestConfig> = {},
) {
  // ...mapped back to the original API name internally
  const pet_id = petId

  return client({
    method: 'DELETE',
    url: `/pet/${pet_id}`,
    ...config,
  })
}
typescript
await deletePet(42)
typescript
// Function parameters mirror the OpenAPI spec
export async function deletePet(
  pet_id: DeletePetPathParams['pet_id'],
  headers?: DeletePetHeaderParams,
  config: Partial<RequestConfig> = {},
) {
  return client({
    method: 'DELETE',
    url: `/pet/${pet_id}`,
    ...config,
  })
}

pathParamsType

How URL path parameters appear in the generated function signature. Affects only path params; query/header params follow paramsType.

  • 'inline' (default) — each path param is a positional argument: getPetById(petId).
  • 'object' — path params are wrapped in a single object: getPetById({ petId }).
Type: 'object' | 'inline'
Required: false
Default: 'inline'
typescript
export async function getPetById(
  petId: GetPetByIdPathParams,
) {
  // ...
}
typescript
export async function getPetById(
  { petId }: GetPetByIdPathParams,
) {
  // ...
}

dataReturnType

Shape of the value returned from each generated client function.

  • 'data' returns only the response body (response.data). Concise and matches what most apps need.
  • 'full' returns the full response config — body, status code, headers, and the original request. Use this when callers need to inspect headers or status.
Type: 'data' | 'full'
Required: false
Default: 'data'
typescript
export async function getPetById<TData>(
  petId: GetPetByIdPathParams,
): Promise<ResponseConfig<TData>['data']> {
  // ...
}
typescript
const pet = await getPetById(1)
//    ^? Pet
typescript
export async function getPetById<TData>(
  petId: GetPetByIdPathParams,
): Promise<ResponseConfig<TData>> {
  // ...
}
typescript
const response = await getPetById(1)
//    ^? ResponseConfig<Pet>
console.log(response.status, response.headers)
const pet = response.data

baseURL

Base URL prepended to every request URL in the generated client. When omitted, the URL comes from the OpenAPI spec's servers[0].url (or whichever index the adapter is configured to read).

Set this when the generated client should point at a different environment (staging, production) than the one written in the spec.

Type: string
Required: false
typescript
import { defineConfig } from 'kubb'
import { pluginClient } from '@kubb/plugin-client'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginClient({
      baseURL: 'https://petstore.swagger.io/v2',
    }),
  ],
})

group

Splits generated files into subfolders based on the operation's tag, so each tag in your OpenAPI spec gets its own directory.

Without group, every file lands in the plugin's output.path folder. With group, files are bucketed under {output.path}/{groupName}/, where groupName is derived from the operation's first tag.

Type: Group
Required: false

TIP

Use group to mirror your API's domain structure (pet, store, user) in the generated code. Combine it with output.barrel: { type: 'named', nested: true } to get per-tag barrel files.

typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      group: {
        type: 'tag',
        name: ({ group }) => `${group}Controller`,
      },
    }),
  ],
})

With the configuration above, the generator emits:

text
src/gen/
├── petController/
│   ├── AddPet.ts
│   └── GetPet.ts
└── storeController/
    ├── CreateStore.ts
    └── GetStoreById.ts

group.type

Property used to assign each operation to a group. Required whenever group is set.

Today only 'tag' is supported: Kubb reads the first tag on the operation (operation.getTags().at(0)?.name) and uses it as the group key. Operations without a tag are placed in a default group.

Type: 'tag'
Required: true

NOTE

Required: true* is conditional — only required when the parent group option is used. group itself stays optional.

group.name

Function that builds the folder/identifier name from a group key (the operation's first tag).

Type: (context: GroupContext) => string
Required: false
Default: (ctx) => \${ctx.group}Requests``

include

Restricts generation to operations that match at least one entry in the list. Anything not matched is skipped.

Each entry filters by one of:

  • tag — the operation's first tag in the OpenAPI spec.
  • operationId — the operation's operationId.
  • path — the URL pattern ('/pet/{petId}').
  • method — HTTP method ('get', 'post', ...).
  • contentType — the media type of the request body.

pattern accepts either a string (exact match) or a RegExp for fuzzy matches.

Type: Array<Include>
Required: false
Type definition
typescript
export type Include = {
  type: 'tag' | 'operationId' | 'path' | 'method' | 'contentType'
  pattern: string | RegExp
}
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      include: [
        { type: 'tag', pattern: 'pet' },
      ],
    }),
  ],
})
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      include: [
        { type: 'method', pattern: 'get' },
        { type: 'path', pattern: /^\/pet/ },
      ],
    }),
  ],
})

exclude

Skips any operation that matches at least one entry in the list. The opposite of include.

Each entry filters by one of:

  • tag — the operation's first tag.
  • operationId — the operation's operationId.
  • path — the URL pattern ('/pet/{petId}').
  • method — HTTP method ('get', 'post', ...).
  • contentType — the media type of the request body.

pattern accepts a plain string or a RegExp. When both include and exclude are set, exclude wins.

Type: Array<Exclude>
Required: false
Type definition
typescript
export type Exclude = {
  type: 'tag' | 'operationId' | 'path' | 'method' | 'contentType'
  pattern: string | RegExp
}
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      exclude: [
        { type: 'tag', pattern: 'store' },
      ],
    }),
  ],
})
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      exclude: [
        { type: 'operationId', pattern: 'deletePet' },
        { type: 'method', pattern: 'delete' },
      ],
    }),
  ],
})

override

Applies a different set of plugin options to operations that match a pattern. Use this when most of your API should follow the global config, but a handful of endpoints need different treatment.

Each entry has the same type and pattern shape as include/exclude, plus an options object that overrides the plugin's options for matched operations.

Entries are evaluated top to bottom. The first matching entry's options is merged onto the plugin defaults; later entries do not stack.

Type: Array<Override>
Required: false
Type definition
typescript
export type Override = {
  type: 'tag' | 'operationId' | 'path' | 'method' | 'contentType'
  pattern: string | RegExp
  options: PluginOptions
}
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      enumType: 'asConst',
      override: [
        {
          type: 'tag',
          pattern: 'user',
          options: { enumType: 'literal' },
        },
      ],
    }),
  ],
})

generators experimental

Adds custom generators that run alongside the plugin's built-in generators. Each generator can emit additional files or post-process existing ones using the plugin's AST and options.

Use this when you need output the plugin does not produce out of the box (a custom client wrapper, an extra index, a metadata file). For end-to-end guidance, see Creating plugins.

Type: Array<Generator<PluginCypress>>
Required: false

WARNING

Generators are an experimental, low-level API. The signature may change between minor releases.

transformer

Modifies AST nodes before they are printed to source code. Use this when you need to rewrite operation IDs, drop descriptions, or change schema metadata without forking the generator.

Each visitor method (e.g. schema, operation) receives the node and a context object. Return a new node to replace it, or return undefined to leave it untouched. Methods you omit keep the plugin's default behavior.

Type: Visitor
Required: false

TIP

Use transformer to rewrite node properties before printing. For changing the names of generated symbols and files, use resolver instead.

typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      transformer: {
        schema(node) {
          return { ...node, description: undefined }
        },
      },
    }),
  ],
})
typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs({
      transformer: {
        operation(node) {
          return { ...node, operationId: `api_${node.operationId}` }
        },
      },
    }),
  ],
})

Dependencies

This plugin requires the following plugins to be installed:

Example

typescript
import { defineConfig } from 'kubb'
import { pluginTs } from '@kubb/plugin-ts'
import { pluginCypress } from '@kubb/plugin-cypress'

export default defineConfig({
  input: { path: './petStore.yaml' },
  output: { path: './src/gen' },
  plugins: [
    pluginTs(),
    pluginCypress({
      output: {
        path: './cypress',
        barrel: { type: 'named' },
        banner: '/* eslint-disable */',
      },
      group: {
        type: 'tag',
        name: ({ group }) => `${group}Requests`,
      },
    }),
  ],
})
typescript
import { getPetByIdRequest } from '../gen/cypress/petRequests'

describe('Pet API', () => {
  it('returns the pet by id', () => {
    getPetByIdRequest(1).then((response) => {
      expect(response.status).to.eq(200)
      expect(response.body.id).to.eq(1)
    })
  })
})