Why is Jest still requiring a mocked module?

旧巷老猫 提交于 2020-01-04 07:16:04

问题


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')

Console output

PASS  test.js
  ✎ todo 1 test

console.log foo.js:1
Hello

What's up with that?


回答1:


This has tripped me up a couple of times.

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.

Two possible solutions:

  • Don't run code in the top level of the module: instead export a function which runs the code.
  • Provide your own mock implementation so it doesn't need to introspect the module jest.mock('./foo', () => {})


来源:https://stackoverflow.com/questions/55632255/why-is-jest-still-requiring-a-mocked-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!