DEV Community

Cover image for Testing Callback Functions with Jest
Kota Ito
Kota Ito

Posted on

Testing Callback Functions with Jest

When writing unit tests, you may encounter a scenario where you need to test a function that is passed as an argument to another function. Here's a practical example to demonstrate how you can achieve this using Jest.

Consider the following code as an example:

import {functionA} from 'path'

const exFunction=(functionB)=>{
  functionA(arg1,(arg2)=>{
    FunctionB(arg2)
  })
}
Enter fullscreen mode Exit fullscreen mode

In this example, exFunction calls functionA, passing it a callback function. functionA then calls this callback with arg2.
It's important to note that the callback function is not called within exFunction directly. So we can not simply test the callback function by calling exFunction.

To test the callback function, we can use Jest's spyOn method to mock the implementation of functionA. This allows us to control its behaviour and ensure the callback function is executed with the desired argument. Here’s how you can do it:

First, import the module containing functionA and exFunction:

import * as functionAFile from 'path';
Enter fullscreen mode Exit fullscreen mode

Next, use jest.spyOn to mock functionA. We will change its implementation to call the callback function with a predefined argument (arg2):

const arg2 = 'dummyArg';
jest.spyOn(functionAFile, 'functionA').mockImplementation((_arg1, callback) => {
  callback(arg2);
});
Enter fullscreen mode Exit fullscreen mode

Now, let's write the test case to verify that functionB is called with arg2:

import {exFunction} from 'path'
import * as functionAFile from 'path'; // Import the entire module to spy on functionA

const arg2 = 'dummyArg';

// Mock functionA to call the callback with arg2
jest.spyOn(functionAFile, 'functionA').mockImplementation((_arg1, callback) => {
  callback(arg2);
});

it('should call functionB with arg2', () => {
  const functionB = jest.fn(); // Create a mock function for functionB

  // Call exFunction with functionB as the argument
  exFunction(functionB);

  // Verify that functionB was called with arg2
  expect(functionB).toHaveBeenCalledWith(arg2);
});
Enter fullscreen mode Exit fullscreen mode

In this test:

  • We use jest.fn() to create a mock function for functionB.

  • We call exFunction with functionB as its argument.

  • Finally, we use expect to assert that functionB was called with arg2. By mocking functionA and controlling its behavior, we can effectively test the callback function and ensure our code behaves as expected.

Top comments (0)