问题
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