How to spy on a default exported function with Jest?

后端 未结 3 413
粉色の甜心
粉色の甜心 2020-12-29 03:36

Suppose I have a simple file exporting a default function:

// UniqueIdGenerator.js
const uniqueIdGenerator = () => Math.random().toString(36).substring(2,         


        
相关标签:
3条回答
  • 2020-12-29 04:27

    I ended up ditching the default export:

    // UniqueIdGenerator.js
    export const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);
    

    And then I could use and spy it like this:

    import * as UniqueIdGenerator from './UniqueIdGenerator';
    // ...
    const spy = jest.spyOn(UniqueIdGenerator, 'uniqueIdGenerator');
    

    Some recommend wrapping them in a const object, and exporting that. I suppose you can also use a class for wrapping.

    However, if you can't modify the class there's still a (not-so-nice) solution:

    import * as UniqueIdGenerator from './UniqueIdGenerator';
    // ...
    const spy = jest.spyOn(UniqueIdGenerator, 'default');
    
    0 讨论(0)
  • 2020-12-29 04:27

    In some cases you have to mock the import to be able to spy the default export:

    import * as fetch from 'node-fetch'
    
    jest.mock('node-fetch', () => ({
      default: jest.fn(),
    }))
    
    jest.spyOn(fetch, 'default')
    
    0 讨论(0)
  • 2020-12-29 04:27

    one could also mock the import and pass the original implementation as mock implementation, like:

    import uniqueIdGenerator from './UniqueIdGenerator'; // this import is a mock already
    
    jest.mock('./UniqueIdGenerator.js', () => {
      const original = jest. requireActual('./UniqueIdGenerator')
      return {
         __esModule: true,
         default: jest.fn(original.default)
      }
    })
    
    test(() => {
      expect(uniqueIdGenerator).toHaveBeenCalled()
    })
    
    0 讨论(0)
提交回复
热议问题