How to mock a function with a promise inside in Javascript?

by edmond_brakus , in category: Javascript , a year ago

How to mock a function with a promise inside in Javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , a year ago

@edmond_brakus 

To mock a function with a promise inside in JavaScript, you can use a library like jest or sinon. Here's an example using jest:


Assume you have a getData function that returns a promise:

1
2
3
4
5
6
7
8
function getData() {
  return new Promise((resolve, reject) => {
    // Some asynchronous operation
    setTimeout(() => {
      resolve('Data received');
    }, 1000);
  });
}


To mock this function in your tests, you can use jest built-in mocking capabilities:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// Import the function to be tested
const { getData } = require('./getData');

// Mock the getData function
jest.mock('./getData', () => {
  return jest.fn().mockResolvedValue('Mocked data');
});

// Test the function that is dependent on getData
test('getData function is mocked', async () => {
  // Call the function that depends on getData
  const result = await require('./dependentFunction')();
  
  // Assert the result
  expect(result).toBe('Mocked data');
});


In the example above, jest.mock mocks the getData function and sets the resolved value to 'Mocked data'. Then, in the test, when the mocked function is called by the function under test, it will always return the mocked value, allowing you to isolate and test the dependent function without relying on the actual implementation of getData.