Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

javascript - How to mock third party modules with Jest

I've got current import in my test target:

import sharp from 'sharp'

and using it with in my same test target:

return sharp(local_read_file)
    .raw()
    .toBuffer()
    .then(outputBuffer => {

In my test, I'm doing below to mock sharp functions:

jest.mock('sharp', () => {
  raw: jest.fn()
  toBuffer: jest.fn()
  then: jest.fn()
})

but I'm getting:

  return (0, _sharp2.default)(local_read_file).
                             ^
TypeError: (0 , _sharp2.default) is not a function

Is there a way we can mock all Sharp module functions using Jest with the function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to mock it like this :

jest.mock('sharp', () => () => ({
        raw: () => ({
            toBuffer: () => ({...})
        })
    })

First you need to return function instead of an object, cause you call sharp(local_read_file). This function call will return an object with key raw which holds another function and so on.

To test on the every of your functions was called you need to create a spy for every of the function. As you can't to this in the initial mock call, you can mock it initially with a spy and add the mocks later on:

jest.mock('sharp', () => jest.fn())

import sharp from 'sharp' //this will import the mock

const then = jest.fn() //create mock `then` function
const toBuffer = jest.fn({()=> ({then})) //create mock for `toBuffer` function that will return the `then` function
const raw = jest.fn(()=> ({toBuffer}))//create mock for `raw` function that will return the `toBuffer` function
sharp.mockImplementation(()=> ({raw})) make `sharp` to return the `raw` function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...