What is babel-plugin-jest-hoist?
The babel-plugin-jest-hoist npm package is designed to work with Jest, a popular JavaScript testing framework. It allows Jest to hoist `jest.mock`, `jest.unmock`, `jest.enableAutomock`, `jest.disableAutomock`, `jest.useFakeTimers`, `jest.useRealTimers`, `jest.setMock`, and `jest.clearAllMocks` calls to the top of the file. This is necessary because Jest needs to isolate modules for mocking before they are used in tests, and doing so manually can be error-prone and tedious.
What are babel-plugin-jest-hoist's main functionalities?
Hoisting jest.mock calls
Automatically hoists `jest.mock` calls to the top of the file, ensuring that modules are mocked before any other code execution.
"use strict";\njest.mock('moduleName');\nconsole.log('This is a test.');"
Hoisting jest.useFakeTimers calls
Automatically hoists `jest.useFakeTimers` calls to the top, allowing tests to use fake timers from the start.
"use strict";\njest.useFakeTimers();\nconsole.log('This is a test with fake timers.');"
Other packages similar to babel-plugin-jest-hoist
babel-plugin-rewire
Similar to babel-plugin-jest-hoist, babel-plugin-rewire allows for modifying module internals, such as variables and functions, for testing purposes. However, it focuses on enabling the rewire functionality rather than specifically working with Jest's global methods.
ts-jest
While ts-jest is a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript, it includes features for handling module mocking and hoisting in a way that's compatible with TypeScript, offering a similar but TypeScript-focused functionality.
babel-plugin-jest-hoist
Babel plugin to hoist jest.disableAutomock
, jest.enableAutomock
, jest.unmock
, jest.mock
, calls above import
statements. This plugin is automatically included when using babel-jest.
Installation
$ npm install babel-plugin-jest-hoist
Usage
Via .babelrc
(Recommended)
.babelrc
{
"plugins": ["jest-hoist"]
}
Via CLI
$ babel --plugins jest-hoist script.js
Via Node API
require('babel-core').transform('code', {
plugins: ['jest-hoist'],
});