Use expect.order with Jest
This guide adds expect.order to Jest. @repobuddy/test is ESM only, so Jest must load the setup file and tests as
ES modules.
Checked with Jest 30.4 on Node.js 24, using .js test files in a "type": "module" package.
-
Install the package:
Terminal window pnpm add -D @repobuddy/test -
Create
setup.js. It installsorderon theexpectfrom@jest/globals:import { expect } from '@jest/globals'import { installOrder } from '@repobuddy/test'installOrder(expect) -
Register it in
jest.config.jswithsetupFilesAfterEnv:export default {setupFilesAfterEnv: ['./setup.js'],testEnvironment: 'node',transform: {},} -
Run Jest with ESM support turned on:
Terminal window NODE_OPTIONS=--experimental-vm-modules npx jestWithout it, a CommonJS test that calls
require('@repobuddy/test')fails withCannot find module '@repobuddy/test'. -
Write a test:
import { expect, it } from '@jest/globals'import { InvalidOrder } from '@repobuddy/test'it('passes when steps run in order', () => {const o = expect.order.plan(2)o.once(1)o.once(2)o.end()})it('throws InvalidOrder when a planned step is missing', () => {const o = expect.order.plan(2)o.once(1)expect(() => o.end()).toThrow(InvalidOrder)})The global
expectis the same object, soexpect.orderalso works without importing@jest/globals. -
For TypeScript test files, add a declaration file (for example
types/jest-order.d.ts) that extends the type of theexpectyou use.With
expectimported from@jest/globals:import type { ExpectWithOrder } from '@repobuddy/test'declare module 'expect' {interface BaseExpect extends ExpectWithOrder {}}With the global
expectfrom@types/jest:import type { ExpectWithOrder } from '@repobuddy/test'declare global {namespace jest {interface Expect extends ExpectWithOrder {}}}declare module 'expect'needs theexpectpackage to be resolvable from your project. If TypeScript reportsTS2664: Invalid module name in augmentation, addexpectto your dev dependencies.Do not augment
@jest/expect: itsexpecttype is a type alias, so the augmentation has no effect andexpect.orderstill reportsTS2339.For a TypeScript transform in Jest, see
@repobuddy/jest.
Finished files
Section titled “Finished files”export default { setupFilesAfterEnv: ['./setup.js'], testEnvironment: 'node', transform: {},}import { expect } from '@jest/globals'import { installOrder } from '@repobuddy/test'
installOrder(expect)Verify
Section titled “Verify”Run NODE_OPTIONS=--experimental-vm-modules npx jest. Both tests from step 5 pass:
Tests: 2 passed, 2 total