avajs/ava · error · Error

The \u2018ava\u2019 module can only be imported in test file

Error message

The \u2018ava\u2019 module can only be imported in test files

What it means

AVA's test files must be executed by the AVA CLI, which sets up the worker environment (including injectable options). guard-environment.js detects when the 'ava' module is imported outside that environment: if run as a plain node script it prints instructions and exits; otherwise (e.g. imported from non-test code or a different runner) it throws this Error.

Source

Thrown at lib/worker/guard-environment.js:16

import path from 'node:path';
import process from 'node:process';

import {isRunningInThread, isRunningInChildProcess} from './utils.js';

// Check if the test is being run without AVA cli
if (!isRunningInChildProcess && !isRunningInThread) {
	if (process.argv[1]) {
		const fp = path.relative('.', process.argv[1]);

		console.log();
		console.error(`Test files must be run with the AVA CLI:\n\n    $ ava ${fp}\n`);

		process.exit(1); // eslint-disable-line unicorn/no-process-exit
	} else {
		throw new Error('The \u2018ava\u2019 module can only be imported in test files');
	}
}

View on GitHub (pinned to bbfd946322)

Solutions

  1. Run tests with the AVA CLI: `npx ava` or `npm test` configured to use ava.
  2. Extract shared logic out of test files so production code never imports 'ava'.
  3. Exclude test files from bundlers/coverage/other runners so they are never loaded outside AVA.

Example fix

// before (shared.js used by app)
import {test} from 'ava';
export const helper = ...;

// after (shared.js has no ava import; test file imports both)
// shared.js
export const helper = ...;
// shared.test.js
import test from 'ava';
import {helper} from './shared.js';
Defensive patterns

Strategy: validation

Validate before calling

const isAvaWorker = process.env.NODE_ENV === 'test' && globalThis.__AVA_OPTIONS__ !== undefined; // or check via ava's own guard before importing 'ava'
if (!isAvaWorker) throw new Error('ava can only be imported inside test files run by the AVA CLI');

Type guard

const canImportAva = () => process.argv.some(a => a.includes('ava')) || process.env.AVA_PATH !== undefined;

Prevention

When it happens

Trigger: Requiring/importing 'ava' from a file run with plain `node file.js`; importing the test file from production code; running test files with another test runner (jest, mocha); importing the test file in a browser or bundler context.

Common situations: Running `node test.js` directly instead of `ava`; a tool (coverage, docs generator, bundler) accidentally pulling in a test file; a shared module that imports `ava` and is also used by app code.

Related errors


AI-assisted analysis of avajs/ava@bbfd946322 (2026-09-02). Data as JSON: /api/errors/2b9e2d075fe11ab6. Report an issue: GitHub.