【问题标题】:Jest check if function was called [duplicate]开玩笑检查是否调用了函数[重复]
【发布时间】:2021-12-11 16:31:54
【问题描述】:

我正在使用 Jest 来测试一些实用功能。

my_util.js:

export function myFunc(i) {
  if (i === 1){
    anotherFunc();
  }
}

另一个_util.js:

export function anotherFunc(i) {
    console.log('in anotherFunc');
}

测试anotherFunc() 被调用的最简单方法是什么?这是我当前的单元测试,它失败了。有没有办法测试一个函数是否被它的名字调用?

import { myFunc } from './my_util.js'

...

  it('myFunc should call anotherFunc', () => {
    const anotherFunc = jest.fn();
    myFunc(1);
    expect(anotherFunc).toHaveBeenCalled();  
  });

结果:

Expected number of calls: >= 1
Received number of calls:    0

【问题讨论】:

  • anotherFunc 定义在哪里(在普通代码中)?
  • anotherFunc 在单独的 .js 文件中定义。我已经更新了帖子以显示这一点。
  • 请分享如何它是导入的?还是全球可用?
  • 已添加导出和导入详细信息
  • 好的,谢谢。这个答案在这里有效。 stackoverflow.com/a/40465435/8282103

标签: javascript jestjs


【解决方案1】:

也许您应该只将anotherFunc 注入myFunc 作为参数,这将使测试更容易:

function myFunc(i, cb) {
  if (i === 1){
    cb();
  }
}
  it('myFunc should call anotherFunc', () => {
    const anotherFunc = jest.fn();
    myFunc(1, anotherFunc);
    expect(anotherFunc).toHaveBeenCalled();  
  });

【讨论】:

    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2019-07-16
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    相关资源
    最近更新 更多