Methods
There are multiple methods available in jest object. Different methods are ideal for various requirements of testing. Each method creates a separate mock function instance or enables another method of mocking.
Here we will go through a range of such methods and explain their functionality. We will also be looking at some of them through examples.
Mock Modules
While testing Javascript code using jest, you may need to mock a module. Mock Modules come to use when the module or the functions it exports are irrelevant to the specific test or when you need to stop something like an API request from trying to access an external resource. There are several methods to mocking modules in jest.
jest.disableAutomock()
Usually, this method is proper when you have a scenario where the number of dependencies you require to mock is much less than the total number of dependencies that you don't. For example, while writing a test for a module that uses a vast number of dependencies that we can reasonably classify as "implementation details" of the module, you would most likely not want to mock them.
Once you call this method, all require() functions will return the real versions of each module instead of a mocked version.
Jest configuration looks something like this.
Program
{
"automock": true
}

You can also try this code with Online Javascript Compiler
Run Code
A very basic example of this method is given below.
Program
//example (eg: utils.js)
export default {
authorize: () => {
return 'token';
},
};

You can also try this code with Online Javascript Compiler
Run Code
Program
//test file (__tests__/disableAutomocking.js)
import utils from '../utils';
jest.disableAutomock();
test('original implementation', () => {
// we have the original execution,
// even after setting the automocking in a jest configuration
expect(utils.authorize()).toBe('token');
});

You can also try this code with Online Javascript Compiler
Run Code
Note: this method was previously known as autoMockOff. While using babel-jest, any calls to disableAutomock will automatically be hoisted to the top of the code block. Use autoMockOff to avoid this behavior explicitly.
jest.enableAutomock()
We use this method to enable automatic Mocking in the module loader. It returns the jest object for chaining.
An example based on the same structure as the one for disableAutomock() will help us understand the use of this method.
Program
//example (utils.js)
export default {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};

You can also try this code with Online Javascript Compiler
Run Code
Program
// test (__tests__/enableAutomocking.js)
jest.enableAutomock();
import utils from '../utils';
test('original implementation', () => {
// we now have the mocked implementation,
expect(utils.authorize._isMockFunction).toBeTruthy();
expect(utils.isAuthorized._isMockFunction).toBeTruthy();
});

You can also try this code with Online Javascript Compiler
Run Code
Note: jest.enableAutomock() method was previously known as autoMockOn. While using babel-jest, calls to enableAutomock are automatically hoisted to the top of the code block. Use autoMockOn to avoid this behavior explicitly.
jest.createMockFromModule(moduleName)
This method is to create a manual mock that extends the behavior of the automatic mock.
It is also found under the alias: .genMockFromModule(moduleName). The name of the function was changed for Jest 26.0.0+
We can use the automatic mocking system to generate a mocked version of the module, given the module's name. Let's examine an example to see how createMockFromModule will mock different data types.
Program
// example javascript (jest.js)
module.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: 'ninja',
boolean: true,
symbol: Symbol.for('a.b.c'),
};

You can also try this code with Online Javascript Compiler
Run Code
Program
// example test javascript (jest.test.js)
const example = jest.createMockFromModule('./jest');
test('should run example code', () => {
// this will create a new mocked function having no formal argument.
expect(example.function.name).toEqual('square');
expect(example.function.length).toEqual(0);
// standard synchronous functions as async function.
expect(example.asyncFunction.name).toEqual('asyncSquare');
expect(example.asyncFunction.length).toEqual(0);
// created a new class having the same interface, member functions and mocked properties.
expect(example.class.constructor.name).toEqual('Bar');
expect(example.class.foo.name).toEqual('foo');
expect(example.class.array.length).toEqual(0);
// creating a deeply cloned version of original object.
expect(example.object).toEqual({
baz: 'foo',
bar: {
fiz: 1,
buzz: [],
},
});
// creating a new empty array while ignoring the original.
expect(example.array.length).toEqual(0);
// creating a new property with the same primitive value as the original property.
expect(example.number).toEqual(123);
expect(example.string).toEqual('ninja');
expect(example.boolean).toEqual(true);
expect(example.symbol).toEqual(Symbol.for('a.b.c'));
});

You can also try this code with Online Javascript Compiler
Run Code
Output

In the above example, the createMockFromModule function mocks different data types in the following way.
- Function - It creates a new function with no formal parameters and returns undefined when called. This function will also apply to async functions.
- Class - It can create a new Class maintaining interface from the original and mocking all the class member functions and properties.
- Object - Creates a new, deeply cloned object, maintaining the object and mocking its values.
- Array - It ignores the original array and creates a new one.
- Primitives - Creates a new property with the same primitive value as the original.
Mock Functions
We use Mock Functions to test links between the code by erasing the actual implementation of a function, capturing calls and parameters passed in those calls, capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values. An explanation of a few of the mock function methods is below.
jest.fn(implementation)
This method returns a new and unused mock function. It also optionally takes implementation parameters. For example,
Program
const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();
// With a mock implementation:
const returnsTrue = jest.fn(() => true);
console.log(returnsTrue()); // true;

You can also try this code with Online Javascript Compiler
Run Code
jest.spyON(object, MethodName, accessType?)
This method creates a mock function that is very similar to jest.fn. jest.spyOn differentiates from jest.fn discussed earlier by also tracking calls to object[methodName]. It returns a jest mock function. For example,
Program
// example (jest.js)
const video = {
play() {
return true;
},
};
module.exports = video;

You can also try this code with Online Javascript Compiler
Run Code
Program
// example test (jest.test.js)
const video = require('./jest');
test('plays video', () => {
const spy = jest.spyOn(video, 'play');
const isPlaying = video.play();
expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(true);
spy.mockRestore();
});

You can also try this code with Online Javascript Compiler
Run Code
The jest.spyOn method can also take an optional third argument of accessType since Jest 22.1.0+ that This argument can either be 'get' or 'set,' which is helpful to spy on a getter or a setter, respectively.
Note: jest.spyOn also calls the spied method by default. This behavior is different from most other test libraries. To overwrite the original function, use, jest.spyOn(object, methodName).mockImplementation(() => customImplementation) or object[methodName] = jest.fn(() => customImplementation);
Mock Timers
Mock Timers unable us swap out timers with functions allowing us to control the passage of time. The native timers functions (setTimeout, setInterval, clearTimeout, clearInterval) are not ideal for a testing environment since they rely on real-time to elapse.
Let us go through a few Mock Timers methods to understand their concept with examples.
jest.useFakeTimers(implementation?: 'modern' | 'legacy')
This method instructs Jest to use fake versions of the standard timer functions (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, setImmediate and clearImmediate) and returns jest object for chaining.
The example below will enable fake timers by calling jest.useFakeTimers(). It will mock out setTimeout and other timer functions with mock functions.
Program
// example (jest.js)
'use strict';
function timerGame(callback) {
console.log('Ready, set, go!');
setTimeout(() => {
console.log("Time's up -- stop!");
callback && callback();
}, 1000);
}
module.exports = timerGame;

You can also try this code with Online Javascript Compiler
Run Code
Program
// example test (jest.test.js)
'use strict';
jest.useFakeTimers();
jest.spyOn(global, 'setTimeout');
test('waiting 1 second before ending the game', () => {
const timerGame = require('./jest');
timerGame();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
});

You can also try this code with Online Javascript Compiler
Run Code
Output

jest.runAllTimers()
This method executes both the macro tasks( all tasks queued by setTimeout(), setInterval(), and setImmediate()) and the micro tasks queue(typically interfaced in node via process.nextTick).
When you call this API method, the method will execute all of the pending macro and micro tasks. If those tasks schedule new tasks, those will be continually exhausted tilt there are no more tasks left in the queue.
We often use this method to synchronously execute setTimeouts during a test to synchronously assert some behavior that would only happen after executing the setTimeout() or setInterval() callbacks.
In the example below, we will use this method to fast-forward time right in the middle of the test. We want to assert that the callback is called after 1 second in the javascript test case from the example for jest.useFakeTimers().
Program
// Add following code after the test code for earlier example.
test('calls the callback after 1 second', () => {
const timerGame = require('./jest');
const callback = jest.fn();
timerGame(callback);
// At this point, the callback should not have been called yet
expect(callback).not.toBeCalled();
// Fast-forward until all timers have been executed
jest.runAllTimers();
// Now our callback should have been called!
expect(callback).toBeCalled();
expect(callback).toHaveBeenCalledTimes(1);
});

You can also try this code with Online Javascript Compiler
Run Code
Output

FAQs
-
What is jest mock?
Mocking is a technique that isolates test subjects by replacing dependencies with objects that can be controlled and inspected. Anything your issue depends on can depend on, but it is usually a module that the subject imports.
-
Where do you put Jest mocks?
We define Manual by writing a module in a __mocks__/ subdirectory and immediately adjacent to the module.
-
What's API mocking?
Imitating realistic mock API responses to requests is done by a mock API server or mock server API. These can be either on your local machine or the public Internet. Responses can be static or dynamic and simulate data the real API would return, matching the schema with data types, objects, and arrays.
-
What is API data?
An API gives a set of defined rules explaining how computers or applications communicate with one another. APIs sit between an application and the webserver and act as an intermediary layer that processes data transfer between systems.
Key Takeaways
In this article, have just scratched the surface when it comes to API methods. There are many more methods in these categories and a few miscellaneous ones. Different testing requirements call for other jest objects.
Jest objects form an essential part of web testing using jest framework. Testing large modules and complex functions requires using API calls and Mocking extensively.
We also established the importance of API methods in testing and briefly went over a few methods with simple examples and explanations. There are many more methods to try and work on in the jest framework.
Hence learning never stops, and there is a lot more to learn.
So head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more. Till then, Happy Learning!