Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么Jest仍然需要模拟模块?_Javascript_Mocking_Jestjs_Node Modules - Fatal编程技术网

Javascript 为什么Jest仍然需要模拟模块?

Javascript 为什么Jest仍然需要模拟模块?,javascript,mocking,jestjs,node-modules,Javascript,Mocking,Jestjs,Node Modules,我正在使用Jest模拟一个模块,因为它包含不应该在测试中运行的代码。但是,我可以从输出中看到模块中的代码正在运行 // foo.js console.log('Hello') // test.js jest.mock('./foo') const foo = require('./foo') test.todo('write some tests') 控制台输出 PASS test.js ✎ todo 1 test console.log foo.js:1 Hello 这是怎么回

我正在使用Jest模拟一个模块,因为它包含不应该在测试中运行的代码。但是,我可以从输出中看到模块中的代码正在运行

// foo.js
console.log('Hello')

// test.js
jest.mock('./foo')
const foo = require('./foo')

test.todo('write some tests')
控制台输出

PASS  test.js
  ✎ todo 1 test

console.log foo.js:1
Hello

这是怎么回事?

这让我有好几次绊倒了

如果不为
jest.mock
提供模拟实现,它将返回一个对象,该对象镜像模拟模块的导出,但每个函数都替换为模拟
jest.fn()
。这是相当整洁的,因为它通常是你想要的。但为了确定模块的导出,它必须首先
要求
它。这就是导致运行
控制台.log
的原因

两种可能的解决办法:

  • 不要在模块的顶层运行代码:而是导出运行代码的函数
  • 提供您自己的mock实现,这样它就不需要内省模块
    jest.mock('./foo',()=>{})