Javascript Jest模拟函数不';当它在另一个函数中被调用时,它不能工作

Javascript Jest模拟函数不';当它在另一个函数中被调用时,它不能工作,javascript,mocking,jestjs,Javascript,Mocking,Jestjs,我认为我对Javascript的理解有一些根本性的错误 在abc.js文件中,我有代码 export function returnBoolean() { return true; } export function output() { return returnBoolean(); } 在测试中,我是这样做的 import * as abc from "../abc"; it("test", () => { abc.returnBoolean = jest.fn();

我认为我对Javascript的理解有一些根本性的错误

在abc.js文件中,我有代码

export function returnBoolean() {
  return true;
}

export function output() {
  return returnBoolean();
}
在测试中,我是这样做的

import * as abc from "../abc";

it("test", () => {
  abc.returnBoolean = jest.fn();
  abc.returnBoolean.mockReturnValue(false);
  expect(abc.returnBoolean()).toBe(false); // This is success
  expect(abc.output()).toBe(false); // This failed because return is true
});
我不知道为什么
abc.output()
返回值为
true


我真的很困惑。任何想法都是值得赞赏的。谢谢

想想看,每当您导入
abc
模块时,该模块内的所有函数都被声明,因此,
output
函数将“绑定”到原始返回布尔值

您的模拟将不适用于原始函数

您有两种选择:

  • 如果
    returnBoolean
    可以位于单独的模块上,则可以使用
  • 如果您能够更改
    output
    方法的接口,那么它将能够从模块外部获取
    returnBoolean
    。 然后您将能够传递给它,
    jest.fn()
    ,并对它做出您的期望
  • output()
    returnBoolean()
    都在同一个文件中,并且
    output()
    直接调用
    returnBoolean()

    模拟
    returnBoolean()
    的模块导出对
    output()
    没有任何影响,因为它没有使用模块,它直接调用
    returnBoolean()

    正如felixmosh所说,将
    returnBoolean()
    移动到另一个模块是能够在
    output()
    中模拟调用
    returnBoolean()
    的一种方法

    另一种方法是简单地将模块导入自身,并使用模块在
    output()
    中调用
    returnBoolean()
    ,如下所示:

    // import the module back into itself
    import * as abc from './abc';
    
    export function returnBoolean() {
      return true;
    }
    
    export function output() {
      return abc.returnBoolean(); // use the module to call returnBoolean()
    }
    

    使用这种方法,您的单元测试应该可以工作。

    每当您导入abc模块时,该模块内的所有函数都会被声明,因此,输出函数会“绑定”到原始的returnBoolean。谢谢你的宝贵提示。不过,你能不能给我解释一下这句话?我不太明白,当你需要文件时,场景后面的过程就会停止,读取文件,加载到内存并执行它。无论何时执行,按照您编写函数的方式,它都会使用模块中指向函数的“指针”。因此,如果以后您试图更改该指针,则不会影响“out”函数本身烧坏的指针。“希望这能让事情变得更清楚。@KunYuTsai让我知道这是否有意义,如果你还有任何问题的话。”