babel-jest-assertions
raw JSON → 0.1.0 verified Mon Apr 27 auth: no javascript
A Babel plugin (v0.1.0) that automatically inserts `expect.assertions(n)` and `expect.hasAssertions()` into Jest test blocks by counting `expect` calls. It supports sync, async, arrow, named, and only tests, including `beforeEach`/`afterEach` blocks. Unlike manual insertion, it eliminates human error and verbosity. Current stable version is 0.1.0; no major releases planned. Minimal alternative to manual assertion count management.
Common errors
error TypeError: babel is not a function ↓
cause Using plugin with Babel 7+ without updating Babel API
fix
Downgrade to Babel 6 or use the Babel 7 compatible fork of this plugin.
error ReferenceError: expect is not defined ↓
cause Plugin inserts `expect.assertions` but `expect` is not in scope (e.g., missing `@jest/globals` import in ESM).
fix
Add
import { expect } from '@jest/globals'; to test files or configure Jest globals properly. error The plugin "babel-jest-assertions" didn't return a function. ↓
cause Using plugin string in Babel config but plugin module not installed.
fix
Run
npm install --save-dev babel-jest-assertions and ensure it's in node_modules. Warnings
gotcha Plugin counts `expect` calls, not actual assertions; non-standard matcher chains may be miscounted. ↓
fix Manually add `expect.assertions(n)` if the count is off, or avoid complex expect chains.
gotcha Does not support dynamically computed assertion counts; `expect.assertions` uses a static integer. ↓
fix Use manual `expect.assertions(0)` or disable plugin for dynamic cases.
breaking In v0.1.0, support for counting `expect` in `beforeEach` and `afterEach` was added; existing tests may fail if those blocks contain assertions they didn't before. ↓
fix Review tests that have assertions in lifecycle hooks; adjust expected counts or add assertions.
gotcha Plugin may not work with custom test wrapper functions (e.g., `describe.each`) if they don't match internal patterns. ↓
fix Ensure test blocks use standard `it`, `test`, `xit`, `fit`, `it.only` only.
Install
npm install babel-jest-assertions yarn add babel-jest-assertions pnpm add babel-jest-assertions Imports
- (plugin) wrong
import babelJestAssertions from 'babel-jest-assertions'correctAdd `'babel-jest-assertions'` to your `.babelrc` plugins array
Quickstart
// .babelrc
{
"plugins": ["babel-jest-assertions"]
}
// test.js
it('counts assertions', () => {
expect(1 + 0).toBe(1);
expect(0 + 1).toBe(1);
});
// Transforms to:
// it('counts assertions', () => {
// expect.hasAssertions();
// expect.assertions(2);
// expect(1 + 0).toBe(1);
// expect(0 + 1).toBe(1);
// });