【问题标题】:How check if static methods is called in Jest?如何检查是否在 Jest 中调用了静态方法?
【发布时间】:2021-05-12 01:04:21
【问题描述】:

我有 ES-6 类,它有静态方法。如何在 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
  });
});

【问题讨论】:

标签: javascript ecmascript-6 jestjs enzyme


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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 回答是一种更好的方法

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 2014-02-02
      • 2012-12-20
      • 2012-02-02
      相关资源
      最近更新 更多