如何检查 Jest 中是否调用了静态方法?

How check if static methods is called in Jest?

我有 ES-6 class,它有静态方法。如何在 Jest 中模拟它们以测试它们是否被调用?

我有 3 个文件

  1. 记录器
class Logger {
  static log = (err) => {
    console.log(err);
  }
}
export default Logger;
  1. 行动
// import Logger './Logger';
export const myAction = () => {
  handleRequest(params).then((response) => {
    // Statements
  }).catch((err) => {
    Logger.log(err);
  });
};
  1. 测试文件
// 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
  });
});

您可以使用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();
});

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

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

您可以在创建实例之前修改 class。

const foo = jest.fn()
const bar = jest.fn()

MyClass.foo = foo
MyClass.bar = bar

const myClass = new MyClass()

myClass.foo()

expect(foo).toHaveBeenCalled()

这是否是正确的方法取决于测试的方式MyClass

编辑:老实说,我认为@lissettdm 的回答是更好的做法