The Jest Object
Объект jest
автоматически помещается в область видимости каждого тестового файла. Методы объекта jest
позволяют создавать mock-объекты и управлять поведением Jest.
Методы #
jest.clearAllTimers()
jest.disableAutomock()
jest.enableAutomock()
jest.fn(implementation)
jest.isMockFunction(fn)
jest.genMockFromModule(moduleName)
jest.mock(moduleName, factory, options)
jest.unmock(moduleName)
jest.doMock(moduleName, factory, options)
jest.dontMock(moduleName)
jest.clearAllMocks()
jest.resetAllMocks()
jest.restoreAllMocks()
jest.resetModules()
jest.runAllTicks()
jest.runAllTimers()
jest.runTimersToTime(msToRun)
jest.runOnlyPendingTimers()
jest.setMock(moduleName, moduleExports)
jest.setTimeout(timeout)
jest.useFakeTimers()
jest.useRealTimers()
jest.spyOn(object, methodName)
Справка #
jest.clearAllTimers()
#
Удаляет все таймеры из системы таймеров.
Это означает, что если были запланированы некие таймеры, которые ещё не выполнились, то они будут удалены и в будущем выполниться не смогут.
jest.disableAutomock()
#
Отключает автоматическое создание mock-объектов в загрузчике модулей.
После вызова этого метода все обращения к require()
будут возвращать реальные версии каждого модуля (а не их mock-версии).
Это обычно полезно, когда у вас есть сценарий, где количество зависимостей, которые вы хотите сымитировать, гораздо меньше, чем количество зависимостей, для которых это не требуется. Например, если вы пишете тест для модуля, который использует большое число зависимостей, которые могут быть расценены, как «детали реализации» модуля, то вы, вероятно, не захотите их имитировать.
Примеры зависимостей, которые могут считаться «деталями реализации», лежат в диапазоне, начиная от встроенных в язык функций (например, метод Array.prototype) и заканчивая более общими служебными методами (underscore/lo-dash, работа с массивами и т.д.) и даже целыми библиотеками, такими как React.js.
Возвращает объект jest
для создания цепочки вызовов.
Примечание: этот метод ранее назывался autoMockOff
. При использовании babel-jest
вызовы disableAutomock
будут автоматически перенесены наверх в текущем блоке кода. Если вы хотите явно избежать этого поведения, используйте autoMockOff
.
jest.enableAutomock()
#
Enables automatic mocking in the module loader.
Возвращает объект jest
для создания цепочки вызовов.
Note: this method was previously called autoMockOn
. When using babel-jest
, calls to enableAutomock
will automatically be hoisted to the top of the code block. Use autoMockOn
if you want to explicitly avoid this behavior.
jest.fn(implementation)
#
Returns a new, unused mock function. Optionally takes a mock implementation.
const mockFn = jest.fn(); mockFn(); expect(mockFn).toHaveBeenCalled(); // With a mock implementation: const returnsTrue = jest.fn(() => true); console.log(returnsTrue()); // true;
jest.isMockFunction(fn)
#
Determines if the given function is a mocked function.
jest.genMockFromModule(moduleName)
#
Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you.
This is useful when you want to create a manual mock that extends the automatic mock's behavior.
jest.mock(moduleName, factory, options)
#
Mocks a module with an auto-mocked version when it is being required. factory
and options
are optional. For example:
// banana.js module.exports = () => 'banana'; // __tests__/test.js jest.mock('../banana'); const banana = require('../banana'); // banana will be explicitly mocked. banana(); // will return 'undefined' because the function is auto-mocked.
The second argument can be used to specify an explicit module factory that is being run instead of using Jest's automocking feature:
jest.mock('../moduleName', () => { return jest.fn(() => 42); }); const moduleName = require('../moduleName'); // This runs the function specified as second argument to `jest.mock`. moduleName(); // Will return '42';
The third argument can be used to create virtual mocks – mocks of modules that don't exist anywhere in the system:
jest.mock('../moduleName', () => { /* * Custom implementation of a module that doesn't exist in JS, * like a generated module or a native module in react-native. */ }, {virtual: true});
Warning: Importing a module in a setup file (as specified by setupTestFrameworkScriptFile
) will prevent mocking for the module in question, as well as all the modules that it imports.
Modules that are mocked with jest.mock
are mocked only for the file that calls jest.mock
. Another file that imports the module will get the original implementation even if run after the test file that mocks the module.
Возвращает объект jest
для создания цепочки вызовов.
jest.unmock(moduleName)
#
Indicates that the module system should never return a mocked version of the specified module from require()
(e.g. that it should always return the real module).
The most common use of this API is for specifying the module a given test intends to be testing (and thus doesn't want automatically mocked).
Возвращает объект jest
для создания цепочки вызовов.
jest.doMock(moduleName, factory, options)
#
When using babel-jest
, calls to mock
will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.
One example when this is useful is when you want to mock a module differently within the same file:
beforeEach(() => { jest.resetModules(); }); test('moduleName 1', () => { jest.doMock('../moduleName', () => { return jest.fn(() => 1); }); const moduleName = require('../moduleName'); expect(moduleName()).toEqual(1); }); test('moduleName 2', () => { jest.doMock('../moduleName', () => { return jest.fn(() => 2); }); const moduleName = require('../moduleName'); expect(moduleName()).toEqual(2); });
Возвращает объект jest
для создания цепочки вызовов.
jest.dontMock(moduleName)
#
When using babel-jest
, calls to unmock
will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.
Возвращает объект jest
для создания цепочки вызовов.
jest.clearAllMocks()
#
Clears the mock.calls
and mock.instances
properties of all mocks. Equivalent to calling .mockClear()
on every mocked function.
Возвращает объект jest
для создания цепочки вызовов.
jest.resetAllMocks()
#
Resets the state of all mocks. Equivalent to calling .mockReset()
on every mocked function.
Возвращает объект jest
для создания цепочки вызовов.
jest.restoreAllMocks()
#
available in Jest 20.1.0+ #
Restores all mocks back to their original value. Equivalent to calling .mockRestore
on every mocked function. Beware that jest.restoreAllMocks()
only works when mock was created with jest.spyOn
; other mocks will require you to manually restore them.
jest.resetModules()
#
Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests.
Пример:
const sum1 = require('../sum'); jest.resetModules(); const sum2 = require('../sum'); sum1 === sum2; // > false (Оба модуля sum являются отдельными "экземплярами" модуля sum.)
Пример в тесте:
beforeEach(() => { jest.resetModules(); }); test('работает', () => { const sum = require('../sum'); }); test('также работает', () => { const sum = require('../sum'); // sum это отличная от предыдущего теста копия модуля sum. });
Возвращает объект jest
для создания цепочки вызовов.
jest.runAllTicks()
#
Exhausts the micro-task queue (usually interfaced in node via process.nextTick
).
When this API is called, all pending micro-tasks that have been queued via process.nextTick
will be executed. Additionally, if those micro-tasks themselves schedule new micro-tasks, those will be continually exhausted until there are no more micro-tasks remaining in the queue.
jest.runAllTimers()
#
Exhausts the macro-task queue (i.e., all tasks queued by setTimeout()
, setInterval()
, and setImmediate()
).
When this API is called, all pending "macro-tasks" that have been queued via setTimeout()
or setInterval()
will be executed. Additionally if those macro-tasks themselves schedule new macro-tasks, those will be continually exhausted until there are no more macro-tasks remaining in the queue.
This is often useful for synchronously executing setTimeouts during a test in order to synchronously assert about some behavior that would only happen after the setTimeout()
or setInterval()
callbacks executed. See the Timer mocks doc for more information.
jest.runAllImmediates()
#
Exhausts all tasks queued by setImmediate()
.
jest.runTimersToTime(msToRun)
#
Executes only the macro task queue (i.e. all tasks queued by setTimeout()
or setInterval()
and setImmediate()
).
When this API is called, all pending "macro-tasks" that have been queued via setTimeout()
or setInterval()
, and would be executed within msToRun
milliseconds will be executed. Additionally if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue, that should be run within msToRun
milliseconds.
jest.runOnlyPendingTimers()
#
Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout()
or setInterval()
up to this point). If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call.
This is useful for scenarios such as one where the module being tested schedules a setTimeout()
whose callback schedules another setTimeout()
recursively (meaning the scheduling never stops). In these scenarios, it's useful to be able to run forward in time by a single step at a time.
jest.setMock(moduleName, moduleExports)
#
Explicitly supplies the mock object that the module system should return for the specified module.
On occasion there are times where the automatically generated mock the module system would normally provide you isn't adequate enough for your testing needs. Normally under those circumstances you should write a manual mock that is more adequate for the module in question. However, on extremely rare occasions, even a manual mock isn't suitable for your purposes and you need to build the mock yourself inside your test.
In these rare scenarios you can use this API to manually fill the slot in the module system's mock-module registry.
Возвращает объект jest
для создания цепочки вызовов.
Note It is recommended to use jest.mock()
instead. The jest.mock
API's second argument is a module factory instead of the expected exported module object.
jest.setTimeout(timeout)
#
Set the default timeout interval for tests and before/after hooks in milliseconds.
Note: The default timeout interval is 5 seconds if this method is not called.
Пример:
jest.setTimeout(1000); // 1 second
jest.useFakeTimers()
#
Instructs Jest to use fake versions of the standard timer functions (setTimeout
, setInterval
, clearTimeout
, clearInterval
, nextTick
, setImmediate
and clearImmediate
).
Возвращает объект jest
для создания цепочки вызовов.
jest.useRealTimers()
#
Instructs Jest to use the real versions of the standard timer functions.
Возвращает объект jest
для создания цепочки вызовов.
jest.spyOn(object, methodName)
#
доступно в версиях Jest 19.0.0+ #
Creates a mock function similar to jest.fn
but also tracks calls to object[methodName]
. Returns a Jest mock function.
Note: By default, jest.spyOn
also calls the spied method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use jest.spyOn(object, methodName).mockImplementation(() => customImplementation)
or object[methodName] = jest.fn(() => customImplementation);
Пример:
const video = { play() { return true; }, }; module.exports = video;
Пример теста:
const video = require('./video'); test('проигрывает видео', () => { const spy = jest.spyOn(video, 'play'); const isPlaying = video.play(); expect(spy).toHaveBeenCalled(); expect(isPlaying).toBe(true); spy.mockReset(); spy.mockRestore(); });