Jest 对象·续2

beforeEach(() => {  jest.resetModules();});test('works', () => {  const sum = require('../sum');});test('works too', () => {  const sum = require('../sum');  // sum is a different copy of the sum module from the previous test.});});

Returns the jest object for chaining.

jest.isolateModules(fn)

jest.isolateModules(fn) goes a step further than jest.resetModules() and creates a sandbox registry for the modules that are loaded inside the callback function. This is useful to isolate specific modules for every test so that local module state doesn’t conflict between tests. This is useful to isolate specific modules for every test so that local module state doesn’t conflict between tests.

let myModule;jest.isolateModules(() => {  myModule = require('myModule');});const otherCopyOfMyModule = require('myModule');

Mock functions

jest.fn(implementation)

Returns a new, unused mock function. Optionally takes a mock implementation. 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.spyOn(object, methodName)

Creates a mock function similar to jest.fn but also tracks calls to object[methodName]. Returns a Jest mock function. Returns a Jest mock function.

Note: By default, jest.spyOn also calls the spied method. This is different behavior from most other test libraries. 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);

Example:

const video = {  play() {    return true;  },};module.exports = video;

Example test:

const video = require('./video');test('plays video', () => {  const spy = jest.spyOn(video, 'play');  const isPlaying = video.play();  expect(spy).toHaveBeenCalled();  expect(isPlaying).toBe(true);  spy.mockRestore();});

jest.spyOn(object, methodName, accessType?)

Since Jest 22.1.0+, the jest.spyOn method takes an optional third argument of accessType that can be either 'get' or 'set', which proves to be useful when you want to spy on a getter or a setter, respectively.

Example:

const video = {  // it's a getter!  const video = {  // it's a getter!  get play() {    return true;  },};module.exports = video;const audio = {  _volume: false,  // it's a setter!  set volume(value) {    this._volume = value;  },  get volume() {    return this._volume;  },};module.exports = audio;  set volume(value) {    this._volume = value;  },  get volume() {    return this._volume;  },};module.exports = audio;

Example test:

const audio = require('./audio');const video = require('./video');test('plays video', () => {  const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get'  const isPlaying = video.play;  expect(spy).toHaveBeenCalled();  expect(isPlaying).toBe(true);  spy.mockRestore();});test('plays audio', () => {  const spy = jest.spyOn(audio, 'volume', 'set'); // we pass 'set'  audio.volume = 100;  expect(spy).toHaveBeenCalled();  expect(audio.volume).toBe(100);  spy.mockRestore();});

jest.clearAllMocks()

Clears the mock.calls and mock.instances properties of all mocks. Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function.

Returns the jest object for chaining.

jest.resetAllMocks()

Resets the state of all mocks. Resets the state of all mocks. Equivalent to calling .mockReset() on every mocked function.

Returns the jest object for chaining.

jest.restoreAllMocks()

Restores all mocks back to their original value. Equivalent to calling .mockRestore() on every mocked function. Restores all mocks back to their original value. Equivalent to calling .mockRestore() on every mocked function. Beware that jest.restoreAllMocks() only works when the mock was created with jest.spyOn; other mocks will require you to manually restore them.

Mock timers

jest.useFakeTimers(implementation?: 'modern' | 'legacy')

Instructs Jest to use fake versions of the standard timer functions (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, setImmediate and clearImmediate as well as Date).

If you pass 'legacy' as an argument, Jest’s legacy implementation will be used rather than one based on @sinonjs/fake-timers.

Returns the jest object for chaining.

jest.useRealTimers()

Instructs Jest to use the real versions of the standard timer functions.

Returns the jest object for chaining.

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. 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 both the macro-task queue (i.e., all tasks queued by setTimeout(), setInterval(), and setImmediate()) and the micro-task queue (usually interfaced in node via process.nextTick).

When this API is called, all pending macro-tasks and micro-tasks will be executed. If those tasks themselves schedule new tasks, those will be continually exhausted until there are no more tasks remaining in the queue. If those tasks themselves schedule new tasks, those will be continually exhausted until there are no more 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. See the Timer mocks doc for more information.

jest.runAllImmediates()

Exhausts all tasks queued by setImmediate().

Note: This function is not available when using modern fake timers implementation

jest.advanceTimersByTime(msToRun)

Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()).

When this API is called, all timers are advanced by msToRun milliseconds. When this API is called, all timers are advanced by msToRun milliseconds. All pending “macro-tasks” that have been queued via setTimeout() or setInterval(), and would be executed within this time frame 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. 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. If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call.