简体   繁体   English

在其他函数中调用时,Jest模拟函数不起作用

[英]Jest mock function doesn't work while it was called in the other function

I believe something fundamentally wrong in my understanding for Javascript. 我相信我对Javascript的理解有些根本错误。

In file abc.js, I have code 在文件abc.js中,我有代码

export function returnBoolean() {
  return true;
}

export function output() {
  return returnBoolean();
}

In the test, I do 在测试中,我做到了

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
});

I don't know why abc.output() return is true . 我不知道为什么abc.output()返回true

I am really confused. 我真的很困惑。 Any thought is really appreciated. 任何想法都非常感激。 Thanks! 谢谢!

output() and returnBoolean() are both in the same file and output() calls returnBoolean() directly. output()returnBoolean()都在同一个文件中, output() returnBoolean()直接调用returnBoolean()

Mocking the module export for returnBoolean() doesn't have any effect on output() since it is not using the module, it is calling returnBoolean() directly. 嘲笑为模块出口returnBoolean()没有任何影响output()因为它不使用模块,它被调用returnBoolean()直接。

Like felixmosh said, moving returnBoolean() to a different module is one way to be able to mock the call to returnBoolean() within output() . 就像felixmosh所说的那样,将returnBoolean()移动到另一个模块是一种能够在output()模拟对returnBoolean()的调用的方法。

The other way is to simply import the module back into itself and use the module to call returnBoolean() within output() like this: 另一种方法是简单地将模块导入自身并使用模块在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()
}

With this approach your unit test should work. 使用这种方法,您的单元测试应该可行。

Think about it, whenever you import abc module, all the function inside that module are declared, therefore, output function get "bounded" to the original returnBoolean. 想想看,无论何时导入abc模块,都会声明该模块中的所有函数,因此, output函数会被“绑定”到原始的returnBoolean。

Your mock won't apply on the original function. 您的模拟不适用于原始功能。

You have 2 choices: 你有2个选择:

  1. If the returnBoolean can be on a separate module, you will able to use jest's mocking mechnisem . 如果returnBoolean可以在一个单独的模块上,你将能够使用jest的模拟mechnisem
  2. If you able to change the interface of output method so it will be able to get the returnBoolean from outside of the module. 如果能够更改output方法的接口,那么它将能够从模块外部获取returnBoolean Then you will be able to pass to it, jest.fn() and make your expectation on it. 然后你就可以传递给它, jest.fn()并对它做出你的期望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM