I'm trying to get jest mocking to work on a relative path. The same code but with mocking fs
worked great, so I'm not sure why trying to mock my own modules doesn't work
// myFile.js
const { cacheFile } = require('./cacheHandler.js')
const myFunc = () => {
cacheFile(file_name)
}
// myFile.spec.js
const myFile = require('./myFile.js')
const cacheHandler = require('./cacheHandler.js')
jest.mock('./cacheHandler.js')
describe("my failing test :( ", () =>{
it("should be able to spy on the function", () => {
cacheHandler.cacheFile = jest.fn()
myFile.myFunc()
expect(cacheHandler.cacheFile).toHaveBeenCalledTimes(1)
}
}
jest claims that the cacheFile() was never called, eventhough when I debug this I can see that it reached this function...
What am I missing?
To mock an imported function with Jest we use the jest. mock() function. jest. mock() is called with one required argument - the import path of the module we're mocking.
To mock inner function with Jest and JavaScript, we should export the inner function in a module. import * as funcBModule from "./funcB"; import { funcA } from "./foo"; describe("helper", () => { test("test funcB", () => { expect(funcBModule. funcB()). toBe("original"); }); test("test funcA", () => { const spy = jest.
To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.
Discussing Jest SpyOn specifically, it can spy or mock a function on an object. It is useful when you want to watch (spy) on the function call and can execute the original implementation as per need. A mock will just replace the original implementation with the mocked one.
You have to mock it like this:
jest.mock('./cacheHandler.js', ()=>({cacheFile: jest.fn()}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With