简体   繁体   中英

how to mock a named import in jest?

I used to have a set up like so:

export class MyClass {
}
export default new MyClass()

then I would do: import myclass from 'libraries/myclass'

now I change it to:

export const myclass = new MyClass()

and importing like so import { myclass } from 'libraries/myclass' which seems to work in my code

however all my jest tests are failing

I'm currently doing:

jest.mock('libraries/myclass', () => ({
    myclassfunction: jest.fn(),
}))

I've tried changing to:

jest.mock('./myclass.js', () => (
  {
    ...(jest.requireActual('./myclass.js')),
    myclassfunc: () => {}
  }
))

but it still fails and when I console.log(myclass) it is coming through as undefined

You can use jest automock featurein your test, do you need to use the factory to mock it?

import { myclass } from 'libraries/myclass';
jest.mock('libraries/myclass'); 

// myclass is now a mock

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM