最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jest mocking on relative path - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Jun 26, 2017 at 6:17 Andreas Köberle 111k58 gold badges280 silver badges307 bronze badges asked Jun 26, 2017 at 4:16 Nick GinantoNick Ginanto 32.1k49 gold badges141 silver badges250 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

You have to mock it like this:

jest.mock('./cacheHandler.js', ()=>({cacheFile: jest.fn()}))
发布评论

评论列表(0)

  1. 暂无评论