# @magic/test

declaratively test your ecmascript module files

no transpiling of either your codebase nor the tests.

fast.

[agent skill](./MAGIC-TEST-SKILL.md) — a ready-to-use skill that teaches coding
agents how to write and debug tests for your project with this runner
(copy `MAGIC-TEST-SKILL.md` into your agent's skill directory, e.g.
`~/.agents/skill/MAGIC-TEST-SKILL.md`).

[html docs](https://magic.github.io/test)

[![NPM version][npm-image]][npm-url]
[![Coverage Status][coveralls-image]][coveralls-url]
[![Greenkeeper badge][greenkeeper-image]][greenkeeper-url]
[![Known Vulnerabilities][snyk-image]][snyk-url]

<!-- [![Linux Build Status][travis-image]][travis-url] -->
<!-- [![Windows Build Status][appveyor-image]][appveyor-url] -->

[npm-image]: https://img.shields.io/npm/v/@magic/test.svg
[npm-url]: https://www.npmjs.com/package/@magic/test
[travis-image]: https://img.shields.io/travis/com/magic/test/master
[travis-url]: https://travis-ci.com/magic/test
[appveyor-image]: https://img.shields.io/appveyor/ci/magic/test/master.svg
[appveyor-url]: https://ci.appveyor.com/project/magic/test/branch/master
[coveralls-image]: https://coveralls.io/repos/github/magic/test/badge.svg
[coveralls-url]: https://coveralls.io/github/magic/test
[greenkeeper-image]: https://badges.greenkeeper.io/magic/test.svg
[greenkeeper-url]: https://badges.greenkeeper.io/magic/test.svg
[snyk-image]: https://snyk.io/test/github/magic/test/badge.svg
[snyk-url]: https://snyk.io/test/github/magic/test

- [install](#install)
- [npm scripts](#npm-scripts)
- [usage](#usage)
- [data/fs driven test suites](#test-suites)
- [writing tests](#tests)
  - [js types](#tests-types)
  - [predicates and values array](#predicates-and-values)
  - [typescript](#tests-typescript)
  - [multiple tests in one file](#tests-multiple)
  - [running tests multiple times](#tests-runs)
  - [promises](#tests-promises)
  - [callback functions](#tests-cb)
  - [run function before / after individual tests](#tests-hooks)
  - [run function before / after suite of tests](#tests-suite-hooks)
  - [beforeEach and afterEach](#tests-each-hooks)
  - [test @magic-modules](#tests-magic-modules)
- [utility functions](#lib)
  - [deep](#lib-deep)
  - [fs](#lib-fs)
- [curry](#lib-curry)
- [log](#lib-log)
- [vals](#lib-vals)
  - [env](#lib-env)
  - [Environment Constants](#lib-env-constants)
  - [promises](#lib-promises)
  - [http](#lib-http)
  - [tryCatch](#lib-trycatch)
  - [error](#lib-error)
  - [version](#lib-version)
- [mock](#lib-mock)
  - [mock.log](#lib-mock-log)
- [has](#lib-has)
  - [DOM Environment](#lib-dom)
  - [svelte (experimental!)](#lib-svelte)
- [svelte kit mocks](#lib-sveltekit-mocks)
  - [compileSvelte and ensureSvelte](#lib-sveltekit-static)
- [Cli / Js Api Usage](#usage)
  - [js api](#usage-js)
  - [cli](#usage-cli)
  - [npm i -g](#usage-global)
  - [Exit Codes](#exit-codes)
  - [Performance Tips](#performance-tips)
  - [Verbose Output](#verbose-output)
  - [Common Pitfalls](#common-pitfalls)
- [Test Isolation](#test-isolation)
  - [\_\_isolate](#test-isolate)
  - [worker reuse](#worker-reuse)

#### <a name="install"></a>getting started

be in a nodejs project.

```bash
npm i --save-dev --save-exact @magic/test

mkdir test
```

create ./test/yourFileToTest.{js,ts}, the filename is used in the test output,
the path should be the same as the file in your src dir, the path is used in the log messages.

```javascript
// ./test/yourLibToTest.{js,ts}
import yourLibToTest from '../path/to/your/lib.js'

export default [
  { fn: () => true, expect: true, info: 'true is true' },
  // note that the function will be called automagically. expect: true is optional.
  { fn: yourLibToTest.returnsTrue, /* expect: true, */ info: 'yourLibToTest returns true' },
  // if you need arguments, call the function. also works with async/await.
  {
    fn: yourLibToTest.withArgs('argument1', 'argument2'),
    expect: 'string',
    info: 'yourLibToTest.withArgs returns "string"',
  },
  // if you absolutely need to nest your function in a function call
  {
    fn: () => yourLibToTest.withArgs('argument1', 'argument2'),
    expect: true,
    info: 'nested functions work.',
  },
]
```

###### <a name="npm-scripts"></a>npm run scripts

edit package.json:

```json5
{
  "scripts": {
    "test": "t -p", // quick test, only failing tests log
    "coverage": "t", // get full test output and coverage reports
  }
}

repeated for easy copy pasting (without comments):
  "scripts": {
    "test": "t -p",
    "coverage": "t",
  }
```

run the tests:

```bash
  npm test
```

run coverage reports and get full test report including from passing tests:

```bash
  npm run coverage
```

This library tests itself, have a look at [the tests](https://github.com/magic/test/tree/master/test)

Check out [@magic/types](https://github.com/magic/types)
and the other @magic libraries for more test examples.

example output, from this repository, lots of worker tests:
(passing test files are silent if -p is passed)

```
### Testing package: @magic/test@0.3.57

Ran 2940 tests in 11.1s. Passed 2940/2940 100%
```

fastest run, from a private project

```
###  Testing package: @artificialmuseum/engine

Ran 90307 tests in 274.5ms. Passed 90307/90307 100%
Ran 90307 tests in 265.5ms. Passed 90307/90307 100%
Ran 90307 tests in 268.1ms. Passed 90307/90307 100%
```

#### self-test workflow (for contributors)

this package tests **itself against its built output**: the `#src/*` import
alias (see `"imports"` in package.json) resolves to `./dist/*`, and the test
files in `test/` import the framework through that alias. so the workflow is:

```bash
npm run build              # tsc + format — REQUIRED after any src/ change
node dist/bin/t.js -p      # run the self test suite (quiet, failures only)
npm run test:native        # run the same test files on node:test (dist/bin/node-test-runner.js)
```

notes:

- skipping `npm run build` means tests run against **stale** dist output.
- test files are type-checked with `tsc -p tsconfig.test.json`; that config
  also resolves `#src/*` against `dist/`, so build before type-checking too.
- `dist/` is tracked in git on purpose — a rebuilt `dist/` is part of the
  committed changeset.

### benchmarks are a lie.

those numbers lie a bit.
real-world finish times are usually 1-2 seconds for smaller projects,
5-15 seconds for bigger ones with lots of svelte components,
mostly coverage, svelte compilation, worker isolation and node startup.

##### <a name="test-suites"></a>data/fs driven test suite creation:

what good tests look like:

- src and test directories have the same structure and files.
- one test file per src file.
- one suite per function.
- one test per feature.

###### Filesystem or Data driven naming for tests

the following directory structure:

```
./test/
  ./suite1.js
  ./suite2.js
```

creates the same output as exporting the following from ./test/index.js does:

```javascript
import suite1 from './suite1.js'
import suite2 from './suite2.js'

export default {
  suite1,
  suite2,
}
```

##### Important

if test/index.js exists, no other files will be loaded by the discovery mechanism.

if test/lib/index.js exists, no other files from that subdirectory will be loaded.

##### <a name="tests"></a>single test, literal value, function or promise

```javascript
export default { fn: true, expect: true, info: 'expect true to be true' }

// expect: true is the default
export default { fn: true, info: 'expect true to be true' }

// if fn is a function expect is the returned value of the function
export default { fn: () => false, expect: false, info: 'expect true to be true' }

// if expect is a function the return value of the test get passed to it
export default { fn: false, expect: t => t === false, info: 'expect true to be true' }

// if fn is a promise the resolved value will be returned
export default { fn: new Promise(r => r(true)), expect: true, info: 'expect true to be true' }

// if expect is a promise it will resolve before being compared to the fn return value
export default { fn: true, expect: new Promise(r => r(true)), info: 'expect true to be true' }

// callback functions can be tested easily too:
import { promise } from '@magic/test'
const fnWithCallback = (err, arg, cb) => cb(err, arg)
export default { fn: promise(fnWithCallback(null, 'arg', (e, a) => a)), expect: 'arg' }
```

###### <a name="tests-types"></a> testing types

types can be compared using [@magic/types](https://github.com/magic/types)

@magic/types is a full-featured type library, zero dependencies.

it is exported from this library for convenience.

```javascript
import { is } from '@magic/test'
export default [
  { fn: () => 'string', expect: is.string, info: 'test if a function returns a string' },
  {
    fn: () => 'string',
    expect: is.length.equal(6),
    info: 'test length of returned value',
  },
  // !!! Testing for deep equality. simple.
  {
    fn: () => [1, 2, 3],
    expect: is.deep.equal([1, 2, 3]),
    info: 'deep compare arrays/objects for equality',
  },
  {
    fn: () => ({
      key: 1,
    }),
    expect: is.deep.different({ value: 1 }),
    info: 'deep compare arrays/objects for difference',
  },
]
```

###### <a name="predicates-and-values"></a> predicates and values array

combine type checks with value checks in a single expect array.
each element is checked independently. all must pass (AND semantics):

```javascript
import { is } from '@magic/test'
export default [
  {
    fn: () => 'wrong',
    expect: [is.string, 'wrong'],
    info: "is a string AND equals 'wrong'",
  },
  {
    fn: () => [1, 2, 3],
    expect: [is.array, [1, 2, 3]],
    info: 'is an array AND deep equals [1, 2, 3]',
  },
  {
    fn: () => ({ key: 'val' }),
    expect: [is.object, { key: 'val' }],
    info: 'is an object AND deep equals',
  },
]
```

mix predicates and value checks freely:

```javascript
export default {
  fn: () => 42,
  expect: [is.number, v => v > 0, 42],
  info: 'is number, is greater than 0, equals 42',
}
```

predicate elements are functions — evaluated with the test result.
non-predicates are compared with strict equality (primitives) or deep equality (objects/arrays).
pure value arrays without functions, like `expect: [1, 2, 3]`, still use deep equality as before.

###### Caveat:

if you want to test if a function is a function, wrap the function,
by default, @magic/test will try to execute the function and use the return value for the expect.

```javascript
import { is } from '@magic/test'
const fnToTest = () => {}
export default {
  fn: () => fnToTest,
  expect: is.function,
  info: 'function is a function',
}
```

###### <a name="tests-typescript"></a> TypeScript support

@magic/test runs `.ts` test files directly — no transpilation.

```javascript
// test/mytest.ts
import type { Test } from '@magic/test'
export default [
  { fn: () => true, expect: true, info: 'TypeScript test works!' }
] satisfies Test[]
```

This requires Node.js 22.18.0 or later.

##### <a name="tests-multiple"></a> multiple tests

multiple tests can be created by exporting an array or object of single test objects.

```javascript
// exporting an array
export default [
  { fn: () => true, expect: true, info: 'expect true to be true' },
  { fn: () => false, expect: false, info: 'expect false to be false' },
]

// or exporting an object with named test arrays
export default {
  multipleTests: [
    { fn: () => true, expect: true, info: 'expect true to be true' },
    { fn: () => false, expect: false, info: 'expect false to be false' },
  ],
}
```

##### <a name="tests-promises"></a>promises

```javascript
import { promise, is, type Test } from '@magic/test'

export default [
  // kinda clumsy, but works. until you try handling errors.
  {
    fn: new Promise(cb => setTimeout(() => cb(true), 2000)),
    expect: true,
    info: 'handle promises',
  },
  // better!
  {
    fn: promise(cb => setTimeout(() => cb(null, true), 200)),
    expect: true,
    info: 'handle promises in a nicer way',
  },
  {
    fn: promise(cb => setTimeout(() => cb(new Error('error')), 200)),
    expect: is.error,
    info: 'handle promise errors in a nice way',
  },
] satisfies Test[]
```

##### <a name="tests-runs"></a>running tests multiple times

Use the `runs` property to run a test multiple times:

```javascript
import { is } from '@magic/test'

export default [
  {
    fn: Math.random(),
    expect: is.number,
    runs: 5,
    info: 'runs the test 5 times and expects all returns to be numbers',
  },
]
```

##### <a name="tests-cb"></a>callback functions

```javascript
import { promise, is } from '@magic/test'

const fnWithCallback = (err, arg, cb) => cb(err, arg)

export default [
  {
    fn: promise(cb => fnWithCallback(null, true, cb)),
    expect: true,
    info: 'handle callback functions as promises',
  },
  {
    fn: promise(cb => fnWithCallback(new Error('oops'), true, cb)),
    expect: is.error,
    info: 'handle callback function error as promise',
  },
]
```

##### <a name="tests-hooks"></a>run functions before and/or after individual tests

Since before and after usually set up globals, all tests with before/after properties will be run in a worker to make sure they do not pollute the globals

```javascript
const after = () => {
  global.testing = 'Test has finished, cleanup.'
}

const before = () => {
  global.testing = false

  // if a function gets returned,
  // this function will be executed once the test finished.
  return after
}

export default [
  {
    fn: () => { global.testing = 'changed in test' },
    // if before returns a function, it will execute after the test.
    before,
    after,
    expect: () => global.testing === 'changed in test',
  },
```

##### <a name="tests-suite-hooks"></a>run functions before and/or after a suite of tests

Suites that use beforeAll, afterAll, beforeEach or afterEach will run in a worker to make sure we do not pollute globals for other suites.

```javascript
import type { TestObject } from '@magic/test'

const afterAll = () => {
  // Suite has finished, cleanup.'
  global.testing = undefined
}

const beforeAll = () => {
  global.testing = false

  // if a function gets returned,
  // this function will be executed once the test suite finished.
  return afterAll
}

const beforeEach = () => {
  // this will run before EACH test in the suite
  global.testing = true
}

const afterEach = () => {
  // this will run after EACH test in the suite
  global.testing = false
}

export default {
  // if beforeAll returns a function, it will execute after the test suite.
  beforeAll,
  // this is optional if beforeall returns a function.
  // in this example, afterAll will trigger twice.
  afterAll,

  // this will run before each test in the suite
  beforeEach,
  // this will run after each test in the suite
  afterEach,

  tests: [
    {
      fn: () => { global.testing = 'changed in test' },
      expect: () => global.testing === 'changed in test',
    },
  ],
} satisfies TestObject
```

**File-based Hooks:**

You can also create `test/beforeAll.js` and `test/afterAll.js` files that run before/after all tests.
If the exported function returns another function, it will be executed after the tests complete.

**Note:** These files must be placed at the **root** `test/` directory (not in subdirectories).

```javascript
// test/beforeAll.js
export default () => {
  global.setup = true
  // optionally return a cleanup function
  return () => {
    global.setup = false
  }
}
```

```javascript
// test/afterAll.js
export default () => {
  // cleanup after all tests
}
```

##### <a name="tests-magic-modules"></a>test @magic-modules

@magic-modules assume all html tags to be globally defined.
to create those globals for your test and check if a @magic-module returns the correct markup, call one of the tags in your test function:

```javascript
export default [
  { fn: () => i('testing'), expect: ['i', 'testing'], info: '@magic/test can now test html' },
]
```

#### <a name="lib">Utility Belt

@magic/test exports some utility functions that make complex test workflows easier.

###### <a name="lib-deep"></a>deep

Exported from [@magic/deep](https://github.com/magic/deep), deep equality and comparison utilities.

```javascript
import { deep, is } from '@magic/test'

export default [
  {
    fn: () => ({ a: 1, b: 2 }),
    expect: deep.equal({ a: 1, b: 2 }),
    info: 'deep equals comparison',
  },
  {
    fn: () => ({ a: 1 }),
    expect: deep.different({ a: 2 }),
    info: 'deep different comparison',
  },
  {
    fn: () => ({ a: { b: 1 } }),
    expect: deep.equal({ a: { b: 1 } }),
    info: 'nested deep equality',
  },
]
```

**Available functions:**

- `deep.equal(a, b)` - deep equality check
- `deep.different(a, b)` - deep difference check
- `deep.contains(container, item)` - deep inclusion check
- `deep.changes(a, b)` - get differences between objects

###### <a name="lib-fs"></a>fs

Exported from [@magic/fs](https://github.com/magic/fs), file system utilities.

```javascript
import { fs } from '@magic/test'

export default [
  {
    fn: async () => {
      const content = await fs.readFile('./package.json', 'utf-8')
      return content.includes('name')
    },
    expect: true,
    info: 'read file content',
  },
]
```

**Common methods:**

- `fs.readFile(path, encoding)` - read file content
- `fs.writeFile(path, data)` - write file content
- `fs.exists(path)` - check if file exists
- `fs.mkdir(path, options)` - create directory
- `fs.rmdir(path)` - remove directory
- `fs.stat(path)` - get file stats
- `fs.readdir(path)` - read directory contents

###### <a name="lib-curry"></a>curry

Currying splits a function's arguments into nested functions.
Useful for shimming functions with many arguments.

```javascript
import { curry } from '@magic/test'

const compare = (a, b) => a === b
const curried = curry(compare)
const shimmed = curried('shimmed_value')

export default {
  fn: shimmed('shimmed_value'),
  expect: true,
  info: 'expect will be called with a and b and a will equal b',
}
```

###### <a name="lib-log"></a>log

log to test output, colors included.

```javascript
import { log } from '@magic/test'

log.debug('Debug info')
log.info('Something happened')
log.warn('Heads up')
log.error('Something went wrong')
log.critical('Game over')
```

supports multiple arguments, just as console.log:

```javascript
log.info('Testing', library, 'at version', version)
```

###### <a name="lib-vals"></a> vals

Exports JavaScript type constants for testing against any value. Useful for fuzzing and property-based testing.

```javascript
import { vals, is } from '@magic/test'

export default [
  { fn: () => 'test', expect: is.string, info: 'test if value is a string' },
  { fn: () => vals.true, expect: true, info: 'boolean true value' },
  { fn: () => vals.email, expect: is.email, info: 'valid email format' },
  { fn: () => vals.error, expect: is.error, info: 'error instance' },
]
```

**Available Constants:**

| Category     | Constants                                                         |
| ------------ | ----------------------------------------------------------------- |
| Primitives   | `true`, `false`, `number`, `num`, `float`, `int`, `string`, `str` |
| Empty values | `nil`, `emptystr`, `emptyobject`, `emptyarray`, `undef`           |
| Collections  | `array`, `object`, `obj`                                          |
| Time         | `date`, `time`                                                    |
| Errors       | `error`, `err`                                                    |
| Colors       | `rgb`, `rgba`, `hex3`, `hex6`, `hexa4`, `hexa8`                   |
| Other        | `func`, `truthy`, `falsy`, `email`, `regexp`                      |

##### <a name="lib-env"></a>env

check the environment, branch your tests on it.

**Available utilities:**

- `isNodeProd` - checks if NODE_ENV is set to production
- `isNodeDev` - checks if NODE_ENV is set to development
- `isProd` - checks if -p flag is passed to the CLI
- `isVerbose` - checks if MAGIC_TEST_VERBOSE=1 is set or -l flag is passed
- `getErrorLength` - returns error length limit from MAGIC_TEST_ERROR_LENGTH env var (0 = unlimited)

##### <a name="lib-env-constants"></a>Environment Constants

environment variables read by @magic/test:

| Variable                              | Description                                                                                                                                            |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `MAGIC_TEST_WORKERS`                  | max parallel workers (same as `--workers`)                                                                                                             |
| `MAGIC_TEST_VERBOSE`                  | set to `1` for verbose output (same as `-l`)                                                                                                           |
| `MAGIC_TEST_ERROR_LENGTH`             | error string limit, `0` = unlimited (same as `--error-length`)                                                                                         |
| `MAGIC_TEST_HTTP_REJECT_UNAUTHORIZED` | set to `false`/`0` to accept self-signed certificates                                                                                                  |
| `MAGIC_TEST_VERBOSE_ERRORS`           | set to `1` for verbose error output (shows error length limits)                                                                                        |
| `MAGIC_TEST_WORKER_REUSE`             | set to `0` to force one fresh worker per test (default: run a file's isolated tests in one shared worker — faster, but tests share module-level state) |
| `MAGIC_TEST_PREWARM`                  | set to `0` to skip the pre-run component-graph prewarm (on by default)                                                                                 |
| `MAGIC_TEST_PREWARM_WORKERS`          | prewarm thread count (default `4`)                                                                                                                     |
| `MAGIC_TEST_TIMEOUT`                  | per-test timeout in ms (same as `--timeout`)                                                                                                           |
| `MAGIC_TEST_DISCOVERY_TIMEOUT`        | per-file discovery/import budget in ms (default 30000, 120000 on a busy machine)                                                                       |
| `MAGIC_TEST_WORKER_TIMEOUT_MS`        | worker round-trip backstop in ms (default 120000, 600000 on a busy machine)                                                                            |
| `MAGIC_TEST_NICE`                     | CPU nice value 0-19 for the test process (same as `--nice`, default 10)                                                                                |
| `MAGIC_TEST_ADAPTIVE`                 | set to `0` to disable load-adaptive worker throttling (also off on CI)                                                                                 |
| `MAGIC_TEST_COMPILE_CACHE`            | set to `0` to disable the persistent svelte/ts compile cache                                                                                           |
| `MAGIC_TEST_SKIP_DTS_TESTS`           | set to `1` to skip the auto-generated .d.ts type tests                                                                                                 |
| `NODE_ENV`                            | set to `production` by the `-p` flag; defaults to `test`                                                                                               |

```javascript
import { env, isProd, isTest, isDev } from '@magic/test'

export default [
  {
    fn: env.isNodeProd,
    expect: process.env.NODE_ENV === 'production',
    info: 'checks if NODE_ENV is production',
  },
  {
    fn: env.isNodeDev,
    expect: process.env.NODE_ENV === 'development',
    info: 'checks if NODE_ENV is development',
  },
  {
    fn: env.isProd,
    expect: process.argv.includes('-p'),
    info: 'checks if -p flag is passed',
  },
  {
    fn: env.isVerbose,
    expect: process.argv.includes('--verbose'),
    info: 'checks if -l or --verbose flag is passed',
  },
  {
    fn: env.getErrorLength,
    expect: undefined, // default, can be overridden by MAGIC_TEST_ERROR_LENGTH
    info: 'get error length limit',
  },
]
```

##### <a name="lib-promises"></a>promises

wrap node callbacks and promises, try/catch handled for you.
resolves to the value, rejects with the error.

```javascript
import { promise, is } from '@magic/test'

export default [
  {
    fn: promise(cb => setTimeout(() => cb(null, true), 200)),
    expect: true,
    info: 'handle promises in a nice way',
  },
  {
    fn: promise(cb => setTimeout(() => cb(new Error('error')), 200)),
    expect: is.error,
    info: 'handle promise errors in a nice way',
  },
]
```

###### <a name="lib-http"></a>http

http/https requests from tests.

```javascript
import { http } from '@magic/test'

export default [
  {
    fn: http.get('https://api.example.com/data'),
    expect: { success: true },
    info: 'fetches data from API',
  },
  {
    fn: http.post('https://api.example.com/users', { name: 'John' }),
    expect: { id: 1, name: 'John' },
    info: 'creates a new user',
  },
  {
    fn: http.post('http://localhost:3000/data', 'raw string'),
    expect: 'raw string',
    info: 'posts raw string data',
  },
]
```

**Error Handling:**

```javascript
import { http, is } from '@magic/test'

export default [
  {
    fn: http.get('https://invalid-domain-that-does-not-exist.com'),
    expect: is.error,
    info: 'rejects on network error',
  },
  {
    fn: http.get('https://api.example.com/nonexistent'),
    expect: res => res.status === 404,
    info: 'handles 404 responses',
  },
]
```

**Note:** The HTTP module automatically handles:

- Protocol detection (HTTP vs HTTPS)
- JSON parsing for responses with `Content-Type: application/json`
- Raw string returns for non-JSON responses
- `rejectUnauthorized` defaults to `true`; pass `rejectUnauthorized: false` (or set `MAGIC_TEST_HTTP_REJECT_UNAUTHORIZED=false`) to accept self-signed certificates

**HttpOptions:**

```javascript
import type { HttpOptions } from '@magic/test'
```

| Option               | Type             | Default | Description                                                         |
| -------------------- | ---------------- | ------- | ------------------------------------------------------------------- |
| `timeout`            | `number`         | `30000` | Request timeout in milliseconds                                     |
| `rejectUnauthorized` | `boolean`        | `true`  | Reject self-signed certs (set `false` for testing with local certs) |
| `maxSize`            | `number`         | -       | Maximum response size in bytes                                      |
| `requestOptions`     | `RequestOptions` | -       | Additional request options                                          |

###### <a name="lib-trycatch"></a> tryCatch

run a function and catch what it throws, without it bubbling into the runtime

```javascript
import { is, tryCatch } from '@magic/test'
const throwing = () => throw new Error('oops')
const healthy = () => true

export default [
  {
    fn: tryCatch(throwing()),
    expect: is.error,
    info: 'function throws an error',
  },
  {
    fn: tryCatch(healthy()),
    expect: true,
    info: 'function does not throw',
  },
]
```

###### <a name="lib-error"></a> error

re-exports [@magic/error](https://github.com/magic/error) — errors with optional names.

```javascript
import { error } from '@magic/test'

export default [
  {
    fn: tryCatch(error('Message', 'E_NAME')),
    expect: e => e.name === 'E_NAME' && e.message === 'Message',
    info: 'Errors have messages and (optional) names.',
  },
]
```

###### <a name="lib-version"></a> version

checks your exports against a spec you write, so export changes make noise. the spec uses @magic/types — every type it exports is a valid spec string.

```javascript
// test/spec.js
import { version } from '@magic/test'

// import your lib as your codebase requires
// import * as lib from '../src/index.js'
// import lib from '../src/index.js

const spec = {
  stringValue: 'string',
  numberValue: 'number',

  objectValue: [
    'obj',
    {
      key: 'Willbechecked',
    },
  ],

  // Test parent object without checking child properties
  objectNoChildCheck: ['obj', false],
}

export default version(lib, spec)
```

**Note:** Using `['obj', false]` in a spec will test that the parent is an object without checking the key/value pairs inside.

###### <a name="lib-mock"></a> mock

spies and mocks for functions.

```javascript
import { mock, tryCatch } from '@magic/test'

export default [
  {
    fn: () => {
      const spy = mock.fn()
      spy('arg1')
      return spy.calls.length === 1 && spy.calls[0][0] === 'arg1'
    },
    expect: true,
    info: 'mock.fn tracks call arguments',
  },
  {
    fn: () => {
      const spy = mock.fn().mockReturnValue('mocked')
      return spy() === 'mocked'
    },
    expect: true,
    info: 'mock.fn.mockReturnValue sets return value',
  },
  {
    fn: async () => {
      const spy = mock.fn().mockThrow(new Error('fail'))
      const caught = await tryCatch(spy)()
      return caught instanceof Error
    },
    expect: true,
    info: 'mock.fn.mockThrow works with tryCatch',
  },
  {
    fn: () => {
      const obj = { greet: () => 'hello' }
      const spy = mock.spy(obj, 'greet', () => 'world')
      const result = obj.greet()
      spy.mockRestore()
      return result === 'world' && obj.greet() === 'hello'
    },
    expect: true,
    info: 'mock.spy replaces and restores methods',
  },
]
```

**mock.fn properties:**

- `calls` - Array of all call arguments
- `returns` - Array of all return values
- `errors` - Array of all thrown errors (null for non-throwing calls)
- `callCount` - Number of times called

**mock.fn methods:**

- `mockReturnValue(value)` - Set return value (chainable)
- `mockThrow(error)` - Set error to throw (chainable)
- `getCalls()` - Get all call arguments
- `getReturns()` - Get all return values
- `getErrors()` - Get all thrown errors

###### <a name="lib-mock-log"></a>mock.log

- `mock.log.log()` - Logs if not NODE_ENV=production
- `mock.log.warn()` - Logs if not NODE_ENV=production
- `mock.log.error()` - Always logs
- `mock.log.time()` - Logs timing if not NODE_ENV=production
- `mock.log.timeEnd()` - Logs timing end if not NODE_ENV=production

##### <a name="lib-has"></a> has

Functions for asserting object properties without needing explicit type annotations or stringifying functions.

```js
import { has, is } from '@magic/test'
```

**has.property(key, check)** - Check a single property. Accepts either a predicate or a literal value

```js
// With predicate
{
  fn: () => handleSuiteHooks({}),
  expect: has.property('afterAllCleanup', is.fn),
  info: 'returns cleanup function',
}

// With literal value (uses is.deep.equal)
{
  fn: () => getUser(),
  expect: has.property('age', 25),
  info: 'user age is 25',
}
```

**has.properties(spec)** - Check multiple properties. Mix predicates and literal values

```js
{
  fn: () => getUser(),
  expect: has.properties({ name: is.string, age: is.num }),
  info: 'user has required properties',
}

// All literals
{
  fn: () => getUser(),
  expect: has.properties({ name: 'John', age: 25 }),
  info: 'exact user match',
}
```

**has.any(spec)** - Check at least one property matches. Accepts predicates or literals

```js
{
  fn: () => parseResult(),
  expect: has.any({ error: is.error, data: is.object }),
  info: 'result has either error or data',
}

// With literals
{
  fn: () => parseResult(),
  expect: has.any({ error: 'not found', data: null }),
  info: 'result has specific error or null data',
}
```

**has.nested(path, predicate)** - Check a nested property path

```js
{
  fn: () => getData(),
  expect: has.nested('user.profile.name', is.string),
  info: 'deep nested property exists',
}
```

**has.string(substring)** - Check if value is a string containing substring

```js
{
  fn: () => error.message,
  expect: has.string('failed to connect'),
  info: 'error message contains helpful context',
},
// can also check multiple args
{
  fn: () => error.message,
  expect: has.string('failed', 'to', 'connect'),
  info: 'error message contains helpful context',
}
```

**has.key(keyName)** - Check if object has a specific key

```js
{
  fn: () => result,
  expect: has.key('data'),
  info: 'result has data key',
}
```

**has.keys(keyNames[])** - Check if object has all specified keys

```js
{
  fn: () => user,
  expect: has.keys(['name', 'email']),
  info: 'user has required fields',
}
```

**has.includes(item)** - Check if array or string contains item (uses deep.equal for arrays)

```js
const roles = ['admin', 'root', 'user']
{
  fn: () => roles,
  expect: has.includes('admin', 'root'),
  info: 'user has admin role',
}
```

**has.oneOf(...options[])** - Check if value equals one of the options (uses deep.equal)

```js
// if only one arg and first arg is an array:
{
  fn: () => status,
  expect: has.oneOf(['pending', 'done', 'failed']),
  info: 'status is a valid value',
},
// also valid
{
  fn: () => status,
  expect: has.oneOf('pending', 'done', 'failed'),
  info: 'status is a valid value',
},
```

**has.matches(regex)** - Check if string matches regex pattern

```js
{
  fn: () => phoneNumber,
  expect: has.matches(/^\d{3}-\d{4}$/),
  info: 'phone number is valid format',
}
```

**has.at(index, check)** - Check the element at a given index of an array. Accepts a predicate, a literal value, or an array of checks (all must pass)

```js
{
  fn: () => getItems(),
  expect: has.at(0, is.string),
  info: 'first item is a string',
}

// multiple checks must all pass
{
  fn: () => getItems(),
  expect: has.at(0, [is.string, item => item === 'first']),
  info: 'first item is the string "first"',
}
```

**has.not** - Negated versions of every has.* check. `has.not.X(...)` passes exactly when `has.X(...)` would fail (pure logical negation)

```js
{
  fn: () => status,
  expect: has.not.oneOf(['pending', 'done']),
  info: 'status is not a valid state',
}

{
  fn: () => error.message,
  expect: has.not.string('timeout'),
  info: 'error is not a timeout',
}

{
  fn: () => user,
  expect: has.not.property('isAdmin', true),
  info: 'user is not an admin',
}

{
  fn: () => items,
  expect: has.not.includes('admin'),
  info: 'items do not contain admin',
}
```

Available: `has.not.property`, `has.not.properties`, `has.not.any`, `has.not.nested`, `has.not.string`, `has.not.at`, `has.not.key`, `has.not.keys`, `has.not.includes`, `has.not.oneOf`, `has.not.matches`

##### <a name="lib-dom"></a>DOM Environment

@magic/test automatically initializes a DOM environment when imported, making browser APIs available in Node.js.

**Available globals:**

- Core: `document`, `window`, `self`, `navigator`, `location`, `history`
- DOM types: `Node`, `Element`, `HTMLElement`, `SVGElement`, `Document`, `DocumentFragment`
- Events: `Event`, `CustomEvent`, `MouseEvent`, `KeyboardEvent`, `InputEvent`, `TouchEvent`, `PointerEvent`
- Forms: `FormData`, `File`, `FileList`, `Blob`
- Networking: `URL`, `URLSearchParams`, `XMLHttpRequest`, `fetch`, `WebSocket`
- Storage: `Storage`, `sessionStorage`, `localStorage`
- Observers: `MutationObserver`, `IntersectionObserver`, `ResizeObserver`
- File APIs: `FileReader`, `AbortController`, `AbortSignal`
- Streams: `ReadableStream`, `WritableStream`, `TransformStream`
- Misc: `DOMParser`, `XMLSerializer`, `TextEncoder`, `TextDecoder`, `atob`, `btoa`
- Timers: `setTimeout`, `setInterval`, `requestAnimationFrame`

**DOM Utilities:**

```javascript
import { initDOM, getDocument, getWindow } from '@magic/test'

// Get the document and window instances
const doc = getDocument()
const win = getWindow()

// Manually re-initialize if needed
initDOM()
```

**Canvas/Image Polyfills:**

- `new Image()` - Parses PNG data URLs to extract dimensions
- `canvas.getContext('2d')` - Returns node-canvas context
- `canvas.toDataURL()` - Serializes canvas to data URL

###### <a name="lib-svelte"></a>Svelte Testing

**Svelte support is VERY experimental and will be expanded whenever we write tests for our libraries. it currently tests about 20 libraries with a varying degree of complexity and handles most edge cases we encountered**

@magic/test has built-in support for testing Svelte 5 components. Compiles Svelte, mounts them in a DOM, and gives you utilities to interact and assert.

Svelte is an **optional** dependency: all component utilities live under the
`@magic/test/svelte` subpath, so importing plain `@magic/test` never touches
svelte. Install it with `npm i -D svelte` when you need component tests.

internally uses happy-dom to create the dom and html elements.

```javascript
import { tryCatch } from '@magic/test'
import { mount } from '@magic/test/svelte'

const component = './path/to/MyComponent.svelte'

export default [
  {
    component,
    props: { message: 'Hello' },
    fn: ({ target }) => target.innerHTML.includes('Hello'),
    expect: true,
    info: 'renders the message prop',
  },
]
```

**Automatic Test Exports**

When testing Svelte 5 components, @magic/test automatically exports `$state` and `$derived` variables, making them accessible in tests without requiring manual exports.

svelte 5 only — svelte 4 components can't do this.

```svelte
<!-- Component.svelte -->
<script>
  let count = $state(0)
  let doubled = $derived(count * 2)
  // No export needed!
</script>

<button class="inc">+</button>
<span>{doubled}</span>
```

```javascript
// Test - works automatically!
import { mount } from '@magic/test/svelte'

export default [
  {
    component: './Component.svelte',
    fn: async ({ component }) => component.count, // 0
    expect: 0,
    info: 'access $state without manual export',
  },
  {
    component: './Component.svelte',
    fn: async ({ component }) => component.doubled, // 0 (derived)
    expect: 0,
    info: 'access $derived without manual export',
  },
]
```

works for every `$state` and `$derived` rune in your component.

**Exported Functions:**

| Function                               | Description                                                                               |
| -------------------------------------- | ----------------------------------------------------------------------------------------- |
| `mount(filePath, options)`             | Mounts a Svelte component and returns `{ target, component, unmount, css }`               |
| `html(target)`                         | Returns the innerHTML of a mounted component's target element                             |
| `text(target)`                         | Returns the textContent of a target element                                               |
| `component(instance)`                  | Returns the component instance for accessing exported values                              |
| `props(target)`                        | Returns an object of attribute name/value pairs from the target element                   |
| `click(target, selector?)`             | Clicks an element (optionally filtered by CSS selector)                                   |
| `trigger(target, eventType, options?)` | Dispatches a custom event on an element                                                   |
| `scroll(target, x, y)`                 | Scrolls an element to x/y coordinates                                                     |
| `createSnippet(renderFn)`              | Creates a raw snippet to pass as a `children` prop (`renderFn`: string or `() => string`) |
| `tick()`                               | svelte's `tick()`, retry-wrapped — await it after interactions                            |

**Test Properties:**

| Property    | Type                                                                                  | Description                                                                                                               |
| ----------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `component` | `string`                                                                              | Path to the .svelte file                                                                                                  |
| `props`     | `object`                                                                              | Props to pass to the component                                                                                            |
| `context`   | `object \| (info: { target: HTMLElement; props: Record<string, unknown> }) => object` | Svelte context option: either static context entries or a factory function receiving the mount target and processed props |
| `fn`        | `function`                                                                            | Test function receiving `{ target, component, unmount }`                                                                  |

**Context Factory**

the `context` option can be a factory function that receives the mount target and processed props — handy for values that depend on the test context.

```javascript
import { mount } from '@magic/test/svelte'
import { tryCatch } from '@magic/test'

const component = './src/lib/svelte/components/Counter.svelte'

export default [
  {
    component,
    fn: async ({ target, context }) => {
      // context is a function that receives the mount target and processed props
      // You can pass dynamic values here
      return context.target.scrollWidth,
    },
    expect: 0,
    info: 'context is a function that receives the mount target',
  },
  {
    component,
    fn: async ({ target, context }) => {
      // pass a computed value derived from the test context
      const computed = context.target.scrollWidth * 2;
      return computed;
    },
    expect: 400,
    info: 'computed value from context is 400',
  },
]
```

**Component state**

```javascript
import { tick } from 'svelte'
import { mount, html } from '@magic/test/svelte'

const component = './src/lib/svelte/components/Counter.svelte'

export default [
  {
    component,
    fn: async ({ target, component }) => {
      // Access exported state from the component
      return component.count
    },
    expect: 0,
    info: 'initial count is 0',
  },
  {
    component,
    fn: async ({ target, component }) => {
      // Click the increment button and check state
      target.querySelector('.increment').click()
      await tick()
      return component.count
    },
    expect: 1,
    info: 'count increments on button click',
  },
]
```

**Error handling**

```javascript
import { tryCatch } from '@magic/test'
import { mount } from '@magic/test/svelte'

const component = './src/lib/svelte/components/MyComponent.svelte'

export default [
  {
    fn: tryCatch(mount, component, { props: null }),
    expect: t => t.message === 'Props must be an object, got object',
    info: 'throws when props is null',
  },
  {
    fn: tryCatch(mount, component, { props: 'invalid' }),
    expect: t => t.message === 'Props must be an object, got string',
    info: 'throws when props is a string',
  },
]
```

**SvelteKit Mocks:**

Mocks SvelteKit's `$app` modules:

```javascript
import { browser, dev, prod, createStaticPage } from '@magic/test/svelte'

export default [
  {
    fn: () => browser,
    expect: true,
    info: 'always true (mocks a browser environment)',
  },
  {
    fn: () => dev,
    expect: process.env.MAGIC_TEST_ENV !== 'production',
    info: 'true unless the run is in production mode (-p)',
  },
  {
    fn: () => prod,
    expect: process.env.MAGIC_TEST_ENV === 'production',
    info: 'true only in production mode (-p)',
  },
  {
    fn: () => {
      const page = createStaticPage({ url: 'http://example.com', params: { id: '1' } })
      return page.url.hostname === 'example.com' && page.params.id === '1'
    },
    expect: true,
    info: 'createStaticPage returns a page object with url/params/state',
  },
]
```

the loader resolves **all** `$app/*` imports to shims, not just environment:

| import                          | you get                                                             |
| ------------------------------- | ------------------------------------------------------------------- |
| `$app/state`                    | `page` proxy (url/params/state), `navigating`, `updated`            |
| `$app/navigation`               | `goto`, `pushState`, `replaceState`, `invalidate`, `beforeNavigate` |
| `$app/stores`                   | legacy `page` / `navigating` readable stores (+ `updated`)          |
| `$app/paths`                    | `resolve`, `match`, `asset`, `base`, `assets`                       |
| `$app/environment` / `$app/env` | `browser`, `dev`, `prod`, `building`, `version`                     |

###### <a name="lib-sveltekit-static"></a>compileSvelte and ensureSvelte

**compileSvelte:**

compile a .svelte file to js/css (async, file path in):

```javascript
import { compileSvelte } from '@magic/test/svelte'

export default [
  {
    fn: async () => {
      const { js } = await compileSvelte('./path/to/button.svelte')
      return typeof js === 'string'
    },
    expect: true,
    info: 'compiles a svelte file to js/css',
  },
]
```

**ensureSvelte:**

Lazy-loads the Svelte package. Throws if Svelte is not installed:

```javascript
import { ensureSvelte } from '@magic/test/svelte'

export default [
  {
    fn: async () => {
      const svelte = await ensureSvelte()
      return svelte.version.startsWith('5')
    },
    expect: true,
    info: 'loads svelte package',
  },
]
```

## <a name="test-isolation"></a>Test Isolation

@magic/test supports test isolation to prevent tests from affecting each other. Tests in the same suite can share state, but you can isolate them:

```javascript
export default [
  // This test runs in isolation from others
  {
    fn: () => {
      const state = { counter: 0 }
      state.counter++
      return state.counter
    },
    expect: 1,
    info: 'isolated test with local state',
  },
]
```

**Global Isolation Mode:**

By default, tests in the same file share global state. To enable strict isolation where each test gets a fresh environment:

### <a name="test-isolate"></a>\_\_isolate

```javascript
// This runs each test in isolation with fresh globals
export const __isolate = true

export default [
  { fn: () => (global.test = 1), expect: 1 },
  { fn: () => global.test === undefined, expect: true, info: 'fresh global state' },
]
```

**Programmatic Detection:**

You can programmatically check if a suite requires isolation using the `suiteNeedsIsolation` utility:

```javascript
import { suiteNeedsIsolation } from '@magic/test'

const needsIsolation = suiteNeedsIsolation(tests)
```

for custom runners / test tooling.

### <a name="worker-reuse"></a>Worker reuse (component tests)

A file's isolated tests run **sequentially in one shared worker** by default: each test re-mounts on the same window, but the imported module graph (the expensive part, ~6 s per fresh worker) is shared — subsequent mounts take ~40 ms. On a 159-test SvelteKit suite this cut wall time from ~22 s to ~15 s, and under machine load it removes most of the rotating per-test timeouts (fewer workers, fewer one-time cold starts inside the per-test timeout budget).

Trade-off: tests in a batch **share module-level state** (no fresh module registry per test; `globalThis` is restored only between suites, not tests). Only use this for suites whose component tests are stateless / props-driven — i.e. they don't rely on module-scoped `$state`, module-scoped stores, or singletons being re-created per test.

Set `MAGIC_TEST_WORKER_REUSE=0` to force one fresh worker per test (full per-test isolation):

```json
"test": "MAGIC_TEST_WORKER_REUSE=0 t -p -w 4 --timeout 60000"
```

#### <a name="usage"></a>Usage

#### <a name="usage-js"></a>js api:

```javascript
// test/index.js

import { run } from '@magic/test'

const tests = {
  lib: [{ fn: () => true, expect: true, info: 'Expect true to be true' }],
}

run(tests)
```

**Programmatic API:**

The `run` function accepts test suites and runs them programmatically:

```javascript
import { run, is } from '@magic/test'

const tests = {
  myLib: [
    { fn: () => true, expect: true, info: 'true is true' },
    { fn: () => 'test', expect: is.string, info: 'returns a string' },
    { fn: () => ({ a: 1 }), expect: is.deep.equal({ a: 1 }), info: 'deep equals' },
  ],
}

// run returns a promise that resolves to a result object
const { failed } = await run(tests)
```

#### <a name="usage-cli"></a>cli

##### package.json (recommended):

Add the magic/test bin scripts to package.json

```json
{
  "scripts": {
    "test": "t -p",
    "coverage": "t"
  },
  "devDependencies": {
    "@magic/test": "github:magic/test"
  }
}
```

then use the npm run scripts

```bash
  npm test
  npm run coverage
```

##### <a name="usage-global"></a>Globally (not recommended):

you can install this library globally,
but adding the dependency and scripts to package.json is better.

everyone sees the dependency, and your shell stays free of clutter

```bash
  npm i -g @magic/test

  // run tests in production mode
  t -p

  // run tests in verbose mode
  t
```

**CLI Flags:**

| Flag             | Aliases                  | Description                                                                 |
| ---------------- | ------------------------ | --------------------------------------------------------------------------- |
| `-p`             | `--production`, `--prod` | Run tests without coverage (faster)                                         |
| `-l`             | `--verbose`, `--loud`    | Show detailed output including passing tests                                |
| `-i`             | `--include`              | Files to include in coverage                                                |
| `-e`             | `--exclude`              | Files to exclude from coverage                                              |
| `--shards`       | `--shard-count`          | Total number of shards (use with `--shard-id`)                              |
| `--shard-id`     |                          | Shard ID (0-indexed, use with `--shards`)                                   |
| `--error-length` |                          | Max length for error strings (default 70, 0 = no limit)                     |
| `--timeout`      | `-t`, `--to`             | Test timeout in ms (default: 30000)                                         |
| `--workers`      | `-w`                     | Max parallel workers (default: auto, env: MAGIC_TEST_WORKERS)               |
| `--slow`         | `-s`, `--timing`         | Show the slowest tests                                                      |
| `--nice`         |                          | CPU nice value 0-19 for the test process (default 10, env: MAGIC_TEST_NICE) |
| `--native`       |                          | Run with the native node --test runner (with coverage)                      |
| `--help`         |                          | Show help text                                                              |

**Note:** `--shards` and `--shard-id` must be used together. `--shard-id` is 0-indexed (0 to N-1).

**Common Usage:**

````bash
# Quick test run (no coverage, fails show errors)
npm test        # or: t -p

# Full test with coverage report
npm run coverage  # or: t

# Verbose output (shows passing tests)
t -l

# Test with coverage for specific files
t -i "src/**/*.js"

# Use glob patterns for include/exclude
t -i "src/**/*.js" -e "**/*.spec.js"

# Run tests with sharding (for parallel CI)
t --shards 4 --shard-id 0

#### Sharding Tests

Run tests in parallel across multiple processes to speed up large test suites:

```bash
# Run 4 shards, this is shard 0 (of 0-3)
t --shards 4 --shard-id 0

# Run shard 1
t --shards 4 --shard-id 1

# Combine with other flags
t -p --shards 4 --shard-id 2
````

tests are distributed with a hash of the test file path:

- same file, same shard, every run
- no test runs twice
- even distribution based on file paths

reproducible sharding plays nice with CI caching.

Add to your `package.json` for CI/CD:

```json
{
  "scripts": {
    "test": "t -p",
    "test:shard:0": "t -p --shards 4 --shard-id 0",
    "test:shard:1": "t -p --shards 4 --shard-id 1",
    "test:shard:2": "t -p --shards 4 --shard-id 2",
    "test:shard:3": "t -p --shards 4 --shard-id 3"
  }
}
```

Or use a single command to run all shards in parallel:

```bash
# Run all 4 shards in parallel and wait for all to complete
npm run test:shard:0 & npm run test:shard:1 & npm run test:shard:2 & npm run test:shard:3 & wait
```

#### Exit Codes

exit codes:

| Exit Code | Meaning                  |
| --------- | ------------------------ |
| `0`       | All tests passed         |
| `1`       | One or more tests failed |

```bash
# Run tests and check exit code
npm test
echo "Exit code: $?"  # 0 = success, 1 = failure
```

#### .d.ts type tests

every run also type-checks the .d.ts files of your project (the `__dts__` suites in the output).
they read types from the tsconfig.json of the tested repository.
`-e` / `--exclude` applies to them too, and `MAGIC_TEST_SKIP_DTS_TESTS=1` skips them entirely.

#### Performance Tips

make runs faster:

**Use the `-p` flag for development:**

```bash
# Fast mode - no coverage, only shows failures and result summary
npm test
# or
t -p
```

**Shard large test suites:**

```bash
# Split tests across multiple processes
t --shards 4 --shard-id 0
```

**Control worker concurrency:**

```bash
# Use fewer workers (keeps CPU threads free for other tasks)
t -w 2

# Or via environment variable
MAGIC_TEST_WORKERS=2 t -p
```

by default, @magic/test auto-detects CPU count and spawns `max(1, min(CPUs - 2, 4))` workers.
on a busy machine it throttles itself (halves between 1x and 2x the core count, drops to 1 above that) —
`MAGIC_TEST_ADAPTIVE=0` or CI disables the throttling, an explicit `-w` bypasses the cap.

**Minimize async overhead:**

```javascript
// Slower: unnecessary async
export default {
  fn: async () => {
    return true
  },
  expect: true,
}

// Faster: sync test
export default {
  fn: () => true,
  expect: true,
}
```

**Use local state instead of globals:**

```javascript
// Slower: global state requires isolation
export const __isolate = true

// Faster: local state is naturally isolated
export default [
  {
    fn: () => {
      const counter = 0
      return ++counter
    },
    expect: 1,
  },
]
```

**Batch related tests:**

```javascript
// Faster: single suite with multiple tests
export default [
  { fn: () => add(1, 2), expect: 3 },
  { fn: () => add(0, 0), expect: 0 },
  { fn: () => add(-1, 1), expect: 0 },
]
```

##### Verbose Error Output

Set `MAGIC_TEST_VERBOSE_ERRORS=1` to see detailed error information during test execution:

- Error messages will include error codes (e.g., `[E_MAGIC_TEST]`)
- Full error stack traces are logged to console
- Import errors show file-specific details
- Runtime errors include the exact error object

for when tests fail and you want to know why.

Example output with `MAGIC_TEST_VERBOSE_ERRORS=1`:

```
3 test file(s) failed to load (continuing):
some-test.js [E_MAGIC_TEST]: Failed to import test file: /path/to/some-test.js
  Error: Cannot find module './nonexistent'
```

#### Common Pitfalls

Avoid these common mistakes when writing tests:

**1. Forgetting to return in async tests:**

```javascript
// Wrong: promise resolves before test checks result
export default {
  fn: async () => {
    const result = await someAsyncFunction()
    // missing return!
  },
  expect: true,
}

// Correct:
export default {
  fn: async () => {
    return await someAsyncFunction()
  },
  expect: true,
}
```

**2. Not wrapping callback functions:**

```javascript
// Wrong: function gets called immediately
export default {
  fn: doSomething(),  // executes immediately!
  expect: true,
}

// Correct: wrap in function to defer execution
export default {
  fn: () => doSomething(),
  expect: true,
}

// Also correct: let @magic/test execute the function
export default {
  fn: doSomething,
  expect: true,
}
```

**3. Mutating shared state between tests:**

```javascript
// Wrong: counter persists between tests
let counter = 0
export default [
  { fn: () => ++counter, expect: 1 },
  { fn: () => ++counter, expect: 1 }, // fails! counter is now 2
]

// Correct: use local state or reset in beforeEach
let counter = 0
const beforeEach = () => { counter = 0 }
export default {
  beforeEach,
  tests: [
    { fn: () => ++counter, expect: 1 },
    { fn: () => ++counter, expect: 1 }, // passes - reset before each
  ],
}
```

**4. Not awaiting async operations:**

```javascript
// Wrong: test finishes before promise resolves
export default {
  fn: () => {
    setTimeout(() => {
      // This never gets checked!
    }, 100)
  },
  expect: true,
}

// Correct: return the promise
export default {
  fn: () => new Promise(resolve => {
    setTimeout(() => resolve(true), 100)
  }),
  expect: true,
}

// Or use the promise helper:
import { promise } from '@magic/test'
export default {
  fn: promise(cb => setTimeout(() => cb(null, true), 100)),
  expect: true,
}
```

**5. Incorrect hook usage:**

```javascript
import type { Test, TestObject } from '@magic/test'

// Wrong: before/after hooks on individual tests, not suites
export default [
  {
    fn: () => true,
    beforeAll: () => {}, // wrong! beforeAll is for suites
    afterAll: () => {},
    expect: true,
  },
] satisfies Test[]

// Correct: hooks at suite level
const beforeAll = () => {}
const afterAll = () => {}
export default {
  beforeAll,
  afterAll,
  tests: [
    { fn: () => true, expect: true },
  ],
} satisfies TestObject
```

##### <a name="error-codes"></a>Error Codes

@magic/test uses error codes to help with debugging and programmatic error handling. You can import these constants from `@magic/test`:

| Code                         | Description                                  |
| ---------------------------- | -------------------------------------------- |
| `ERRORS.E_EMPTY_SUITE`       | Test suite is not exporting any tests        |
| `ERRORS.E_RUN_SUITE_UNKNOWN` | Unknown error occurred while running a suite |
| `ERRORS.E_TEST_NO_FN`        | Test object is missing the `fn` property     |
| `ERRORS.E_TEST_EXPECT`       | Test expectation failed                      |
| `ERRORS.E_TEST_BEFORE`       | Before hook failed                           |
| `ERRORS.E_TEST_AFTER`        | After hook failed                            |
| `ERRORS.E_TEST_BEFORE_EACH`  | BeforeEach hook failed (suite)               |
| `ERRORS.E_TEST_AFTER_EACH`   | AfterEach hook failed (suite)                |
| `ERRORS.E_TEST_FN`           | Test function threw an error                 |
| `ERRORS.E_NO_TESTS`          | No test suites found                         |
| `ERRORS.E_IMPORT`            | Failed to import a test file                 |
| `ERRORS.E_MAGIC_TEST`        | General test execution error                 |

**createError:**

```javascript
import { createError, ERRORS } from '@magic/test'

export default [
  {
    fn: () => createError(ERRORS.E_TEST_NO_FN, 'Missing fn property'),
    expect: e => e.code === 'E_TEST_NO_FN' && e.message === 'Missing fn property',
    info: 'createError creates errors with code and message',
  },
]
```

See [CHANGELOG.md](CHANGELOG.md) for release history.
