为什么Jest仍然需要模拟模块? [英] Why is Jest still requiring a mocked module?

查看:59
本文介绍了为什么Jest仍然需要模拟模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am mocking a module using Jest because it contains code that shouldn't run in the test. However I can see from the output that code in the module is being run.

// 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()替换.这很整洁,因为通常它是您想要的.但是为了确定模块的导出,必须首先require它.这就是导致console.log运行的原因.

If you don't provide a mock implementation to jest.mock it will return an object which mirrors the exports of the mocked module but with every function replaced with a mock jest.fn(). This is pretty neat as it is often what you want. But in order to determine the exports of the module, it must first require it. This is what is causing the console.log to be run.

两种可能的解决方案:

  • 不要在模块的顶层运行代码:而是导出一个运行代码的函数.
  • 提供您自己的模拟实现,因此不需要自检模块jest.mock('./foo', () => {})

这篇关于为什么Jest仍然需要模拟模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆