JEST
___________________________|_____________________________
| | | | | |
Globals Jest Objects Expect Jest Mock Jest Cli Jest Configure
|| Globals || EslintConfig || Expect || Mocks || Jest Objects || Jest Cli || Jest Configure ||
- mockFn.getMockName()
- mockFn.mock.calls
- mockFn.mock.results
- mockFn.mock.instances
- mockFn.mock.contexts
- mockFn.mock.lastCall
- mockFn.mockClear()
- mockFn.mockReset()
- mockFn.mockRestore()
- mockFn.mockImplementation(fn)
- mockFn.mockImplementationOnce(fn)
- mockFn.mockName(name)
- mockFn.mockReturnThis()
- mockFn.mockReturnValue(value)
- mockFn.mockReturnValueOnce(value)
- mockFn.mockResolvedValue(value)
- mockFn.mockResolvedValueOnce(value)
- mockFn.mockRejectedValue(value)
- mockFn.mockRejectedValueOnce(value)
- mockFn.withImplementation(fn, callback)
A simple addition function.
function add(a, b) {
return a + b;
}
A function that simulates fetching data with a delay.
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve("data"), 1000);
});
}
We'll start by mocking the add
function.
// Mocking the add function
const addMock = jest.fn(add);
// Example usage
addMock(2, 3);
console.log(addMock.mock.calls); // Output: [[2, 3]]
console.log(addMock.mock.results); // Output: [{ type: 'return', value: 5 }]
Now, let's mock the fetchData
function.
// Mocking the fetchData function
const fetchDataMock = jest.fn(fetchData);
// Mocking a resolved value
fetchDataMock.mockResolvedValue("mocked data");
// Example usage
fetchDataMock().then(data => console.log(data)); // Output: mocked data
These are particularly useful for mocking asynchronous functions like fetchData
.
fetchDataMock.mockResolvedValueOnce("first call data");
fetchDataMock().then(data => console.log(data)); // Output: first call data
fetchDataMock().then(data => console.log(data)); // Output: mocked data
To simulate a failure in an asynchronous operation:
fetchDataMock.mockRejectedValueOnce(new Error("Failed to fetch"));
fetchDataMock().catch(error => console.log(error.message)); // Output: Failed to fetch
Using mockFn.mockImplementation(fn)
and mockFn.mockImplementationOnce(fn)
for Asynchronous Functions
You can also dynamically change the implementation of an asynchronous function.
fetchDataMock.mockImplementationOnce(() => Promise.resolve("dynamic data"));
fetchDataMock().then(data => console.log(data)); // Output: dynamic data
This example demonstrates how to create and mock both synchronous and asynchronous functions using Jest, showcasing the versatility of Jest's mocking capabilities to simulate different behaviors and scenarios in our tests.