Jest 对象·续1
// banana.jsmodule.exports = () => 'banana';// __tests__/test.jsjest.mock('../banana');const banana = require('../banana'); // banana will be explicitly mocked.banana(); // will return 'undefined' because the function is auto-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);});// This runs the function specified as second argument to `jest.mock`.const moduleName = require('../moduleName');moduleName(); // Will return '42';const moduleName = require('../moduleName');moduleName(); // Will return '42';
When using the factory parameter for an ES6 module with a default export, the __esModule: true property needs to be specified. This property is normally generated by Babel / TypeScript, but here it needs to be set manually. When importing a default export, it’s an instruction to import the property named default from the export object: This property is normally generated by Babel / TypeScript, but here it needs to be set manually. When importing a default export, it’s an instruction to import the property named default from the export object:
import moduleName, {foo} from '../moduleName';jest.mock('../moduleName', () => { return { __esModule: true, default: jest.fn(() => 42), foo: jest.fn(() => 43), };});moduleName(); // Will return 42foo(); // Will return 43
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},); */ }, {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 it runs after the test file that mocks the module. Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module.
Returns the jest object for chaining.
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).
Returns the jest object for chaining.
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);});
Using jest.doMock() with ES6 imports requires additional steps. Follow these if you don’t want to use require in your tests: Follow these if you don’t want to use require in your tests:
-
We have to specify the __esModule: true property (see the jest.mock() API for more information).
-
Static ES6 module imports are hoisted to the top of the file, so instead we have to import them dynamically using import().
-
Finally, we need an environment which supports dynamic importing. Please see Using Babel for the initial setup. Finally, we need an environment which supports dynamic importing. Please see Using Babel for the initial setup. Then add the plugin babel-plugin-dynamic-import-node, or an equivalent, to your Babel config to enable dynamic importing in Node.
beforeEach(() => { jest.resetModules();});test('moduleName 1', () => { jest.doMock('../moduleName', () => { return { __esModule: true, default: 'default1', foo: 'foo1', }; }); return import('../moduleName').then(moduleName => { expect(moduleName.default).toEqual('default1'); expect(moduleName.foo).toEqual('foo1'); });});test('moduleName 2', () => { jest.doMock('../moduleName', () => { return { __esModule: true, default: 'default2', foo: 'foo2', }; }); return import('../moduleName').then(moduleName => { expect(moduleName.default).toEqual('default2'); expect(moduleName.foo).toEqual('foo2'); });});
Returns the jest object for chaining.
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. Use this method if you want to explicitly avoid this behavior.
Returns the jest object for chaining.
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. 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. 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.
Returns the jest object for chaining.
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. The jest.mock API’s second argument is a module factory instead of the expected exported module object.
jest.requireActual(moduleName)
Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.
Example:
jest.mock('../myModule', () => { // Require the original module to not be mocked... jest.mock('../myModule', () => { // Require the original module to not be mocked... const originalModule = jest.requireActual('../myModule'); return { __esModule: true, // Use it when dealing with esModules ...originalModule, getRandom: jest.fn().mockReturnValue(10), };});const getRandom = require('../myModule').getRandom;getRandom(); // Always returns 10
jest.requireMock(moduleName)
Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.
jest.resetModules()
Resets the module registry - the cache of all required modules. Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests.
Example:
const sum1 = require('../sum');jest.resetModules();const sum2 = require('../sum');sum1 === sum2;// > false (Both sum modules are separate "instances" of the sum module.)
Example in a test:
