How to mock third party modules with Jest

前端 未结 1 1601
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 05:27

I\'ve got current import in my test target:

import sharp from \'sharp\'

and using it with in my same test target:

return sh         


        
相关标签:
1条回答
  • 2020-12-19 06:17

    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
    
    0 讨论(0)
提交回复
热议问题