Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jest mocking on relative path

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?

like image 247
Nick Ginanto Avatar asked Jun 26 '17 04:06

Nick Ginanto


People also ask

How do you mock path in Jest?

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.

How do you mock a function inside another function in Jest?

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.

How do you use spyOn function in 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.

What is Jest spyOn?

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.


1 Answers

You have to mock it like this:

jest.mock('./cacheHandler.js', ()=>({cacheFile: jest.fn()}))
like image 178
Andreas Köberle Avatar answered Oct 17 '22 05:10

Andreas Köberle