Jest Mocking

Jest Mocking

What is mocking?

  • When you do the unit test and you need to test the specific parts of your layer, you use mocking.
  • The parts where the layer depends on could be replaced with mocking functions.

Functions

jest.fn

mockReturnValue(value)

  • set what value should be returned
// make mock function
const mockFn = jest.fn();

// mock is empty function so default return value is undefined
mockFn(); // undefined
mockFn(1); // undefined
mockFn([1, 2], { a: "b" }); // undefined

// set mock return value
mockFn.mockReturnValue("I am a mock!"); // I am a mock!
const mock = jest.fn();

mock.mockReturnValue(42);
mock(); // 42

mock.mockReturnValue(63);
mock(); // 63

mockImplementation(value)

  • Originally, there is nothing inside of mock function.
  • MockImplementation is making the mock function that really functions!
//empty mock function
const mockFn = jest.fn();

// Make mock function that really works
mockFn.mockImplementation( (name) => `I am ${name}!` ); 

console.log(mockFn("Dale")); // I am Dale!
// You can also use jest.fn directly, this way is used a lot since it is more understandable
const mockFn = jest.fn( (name) => `I am ${name}!` );

console.log(mockFn("Dale")); // I am Dale!

mockResolvedValue(value) / mockRejectedValue(value)

  • When you wanna use async function and get the resolved value or rejected value, you use mockResolvedValue or mockRejectedValue
  • It remembers how it was called and remember the parameters that was used. You can check how many times they were called or with what parmeters were called by toBeCalledTimes or toBeCalledWith.
test('async resolve test', async () => {
  const asyncMock = jest.fn().mockResolvedValue(43);

  await asyncMock(); // 43
});

test('async reject test', async () => {
  const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));

  await asyncMock(); // throws "Async error"
});
test("mock Test", () => {
   const mockFn = jest.fn();
   mockFn.mockImplementation(name => `I am ${name}`);
     
   mockFn("a");
   mockFn(["b", "c"]);
   
   expect(mockFn).toBeCalledTimes(2); // How many times called? -> 2
   expect(mockFn).toBeCalledWith("a"); // called with a? -> true
   expect(mockFn).toBeCalledWith(["b", "c"]); // called with array? -> true
})

jest.mock

  • jest.fun() : you should set all the mocking functions respectively
  • jest.mock() : make it a group and mock every functions inside all at once
jest.mock('../models/user'); // objects exported from ../models/user.js group mocking
const User = require('../models/user'); // every elements from ../models/user.js are mocked

User.findOrCreate().mockReturnValue() // we can use right away without using jest.fn() 

jest.spyOn

  • Don't mock the function, we are using the function itself
  • can get the result using the function
test('spyOn Test', () => {
   // object
   const calculator = {
      add: (a, b) => a + b, // method
   };

   // add spyon to calculator.add() method 
   const spyFn = jest.spyOn(calculator, 'add');

   // method execution
   const result = calculator.add(2, 3);

   expect(spyFn).toBeCalledTimes(1); // How many times? -> 1
   expect(spyFn).toBeCalledWith(2, 3); // with what parameters? -> parameter 2, 3
   expect(result).toBe(5); // return value is 5? -> true
});

Developing References

https://velog.io/@jay2u8809/Jest-함수를-Mocking-해보자-jest.spyOn
https://fly.io/docs/reference/enveloop/
https://chrisboakes.com/mocking-javascript-class-inner-functions-with-jest/
https://jestjs.io/docs/es6-class-mocks#calling-jestmockdocsenjest-objectjestmockmodulename-factory-options-with-the-module-factory-parameter
https://4sii.tistory.com/623
https://www.daleseo.com/jest-mock-modules/
https://inpa.tistory.com/entry/JEST-📚-모킹-mocking-jestfn-jestspyOn#mockreturnvaluevalue
https://minoo.medium.com/번역-jest-mocks에-대한-이해-34f75b0f7dbe

Developing Report

2025-01-20 - Jest Mocking Report
2025-01-20 - Developing Daily Report
2025-01-4th - Developing Weekly Report