How check if static methods is called in Jest?

I have ES-6 class which is having static methods. How to mock them in Jest to test if they gets called?

I have 3 files

  1. Logger
class Logger {
  static log = (err) => {
    console.log(err);
  }
}
export default Logger;
  1. action
// import Logger './Logger';
export const myAction = () => {
  handleRequest(params).then((response) => {
    // Statements
  }).catch((err) => {
    Logger.log(err);
  });
};
  1. Test file
// import {myAction} from './action';
// import Logger './Logger';
it('should call Logger', () => {
  Logger.log = jest.fn();
  return myAction().then(() => {
    expect(Logger.log).toHaveBeenCalled(); // It is failing
  });
});

Answer

You can use jest.spyOn(object, methodName)

import Logger './Logger';
import {myAction} from './action';

it('should call Logger', async () => {
  const spy = jest.spyOn(Logger, "log");
  await myAction();
  expect(spy).toHaveBeenCalled();
});

or

import Logger './Logger';
import {myAction} from './action';

it('should call Logger', () => {
  const spy = jest.spyOn(Logger, "log");
  return myAction().finally(() => {
    expect(spy).toHaveBeenCalled();
  });
});

Leave a Reply

Your email address will not be published. Required fields are marked *