Jest 对象
The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest’s overall behavior. It can also be imported explicitly by via import {jest} from '@jest/globals'. The methods in the jest object help create mocks and let you control Jest’s overall behavior. It can also be imported explicitly by via import {jest} from '@jest/globals'.
Mock Modules
jest.disableAutomock()
Disables automatic mocking in the module loader.
See automock section of configuration for more information
After this method is called, all require()s will return the real versions of each module (rather than a mocked version).
Jest configuration:
{ "automock": true}
Example:
// utils.jsexport default { authorize: () => { return 'token'; },};
// __tests__/disableAutomocking.jsimport utils from '../utils';jest.disableAutomock();test('original implementation', () => { // now we have the original implementation, // even if we set the automocking in a jest configuration expect(utils.authorize()).toBe('token');});
This is usually useful when you have a scenario where the number of dependencies you want to mock is far less than the number of dependencies that you don’t. For example, if you’re writing a test for a module that uses a large number of dependencies that can be reasonably classified as “implementation details” of the module, then you likely do not want to mock them. For example, if you’re writing a test for a module that uses a large number of dependencies that can be reasonably classified as “implementation details” of the module, then you likely do not want to mock them.
Examples of dependencies that might be considered “implementation details” are things ranging from language built-ins (e.g. Array.prototype methods) to highly common utility methods (e.g. underscore/lo-dash, array utilities, etc) and entire libraries like React.js.
Returns the jest object for chaining.
Note: this method was previously called autoMockOff. 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. Note: this method was previously called autoMockOff. When using babel-jest, calls to disableAutomock will automatically be hoisted to the top of the code block. Use autoMockOff if you want to explicitly avoid this behavior.
jest.enableAutomock()
Enables automatic mocking in the module loader.
Returns the jest object for chaining.
See automock section of configuration for more information
Example:
// utils.jsexport default { authorize: () => { return 'token'; }, isAuthorized: secret => secret === 'wizard',};
// __tests__/enableAutomocking.jsjest.enableAutomock();import utils from '../utils';test('original implementation', () => { // now we have the mocked implementation, expect(utils.authorize._isMockFunction).toBeTruthy(); expect(utils.isAuthorized._isMockFunction).toBeTruthy();});
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. 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.createMockFromModule(moduleName)
renamed in Jest 26.0.0+
Also under the alias: .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.
Example:
// utils.jsexport default { authorize: () => { return 'token'; }, isAuthorized: secret => secret === 'wizard',};
// __tests__/createMockFromModule.test.jsconst utils = jest.createMockFromModule('../utils').default;utils.isAuthorized = jest.fn(secret => secret === 'not wizard');test('implementation created by jest.createMockFromModule', () => { expect(utils.authorize.mock).toBeTruthy(); expect(utils.isAuthorized('not wizard')).toEqual(true);});
This is how createMockFromModule will mock the following data types:
函数
Creates a new mock function. The new function has no formal parameters and when called will return undefined. This functionality also applies to async functions.
Class
Creates a new class. Creates a new class. The interface of the original class is maintained, all of the class member functions and properties will be mocked.
对象
Creates a new deeply cloned object. Creates a new deeply cloned object. The object keys are maintained and their values are mocked.
数组
Creates a new empty array, ignoring the original.
Primitives
Creates a new property with the same primitive value as the original property.
Example:
// example.jsmodule.exports = { function: function square(a, b) { return a * b; }, asyncFunction: async function asyncSquare(a, b) { const result = (await a) * b; return result; }, class: new (class Bar { constructor() { this.array = [1, 2, 3]; } foo() {} })(), object: { baz: 'foo', bar: { fiz: 1, buzz: [1, 2, 3], }, }, array: [1, 2, 3], number: 123, string: 'baz', boolean: true, symbol: Symbol.for('a.b.c'),};
// __tests__/example.test.jsconst example = jest.createMockFromModule('./example');test('should run example code', () => { // creates a new mocked function with no formal arguments. expect(example.function.name).toEqual('square'); expect(example.function.length).toEqual(0); // async functions get the same treatment as standard synchronous functions. expect(example.asyncFunction.name).toEqual('asyncSquare'); expect(example.asyncFunction.length).toEqual(0); // creates a new class with the same interface, member functions and properties are mocked. expect(example.class.constructor.name).toEqual('Bar'); expect(example.class.foo.name).toEqual('foo'); expect(example.class.array.length).toEqual(0); // creates a deeply cloned version of the original object. expect(example.object).toEqual({ baz: 'foo', bar: { fiz: 1, buzz: [], }, }); // creates a new empty array, ignoring the original array. expect(example.array.length).toEqual(0); // creates a new property with the same primitive value as the original property. expect(example.number).toEqual(123); expect(example.string).toEqual('baz'); expect(example.boolean).toEqual(true); expect(example.symbol).toEqual(Symbol.for('a.b.c'));}); expect(example.function.name).toEqual('square'); expect(example.function.length).toEqual(0); // async functions get the same treatment as standard synchronous functions. expect(example.asyncFunction.name).toEqual('asyncSquare'); expect(example.asyncFunction.length).toEqual(0); // creates a new class with the same interface, member functions and properties are mocked. expect(example.class.constructor.name).toEqual('Bar'); expect(example.class.foo.name).toEqual('foo'); expect(example.class.array.length).toEqual(0); // creates a deeply cloned version of the original object. expect(example.object).toEqual({ baz: 'foo', bar: { fiz: 1, buzz: [], }, }); // creates a new empty array, ignoring the original array. expect(example.array.length).toEqual(0); // creates a new property with the same primitive value as the original property. expect(example.number).toEqual(123); expect(example.string).toEqual('baz'); expect(example.boolean).toEqual(true); expect(example.symbol).toEqual(Symbol.for('a.b.c'));});
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: factory and options are optional. 例如:
