davide-scalzo / react-native-mixpanel

A React Native wrapper for Mixpanel tracking
MIT License
455 stars 195 forks source link

Testing with Jest and Enzyme: TypeError: Cannot read property 'sharedInstanceWithToken' of undefined #255

Open ghasemikasra39 opened 3 years ago

ghasemikasra39 commented 3 years ago

When running my test using Jest and Enzyme, I get this error:

  ● Test suite failed to run

    TypeError: Cannot read property 'sharedInstanceWithToken' of undefined

      47 | class MixPanelClient {
      48 |   constructor() {
    > 49 |     Mixpanel.default.sharedInstanceWithToken(
         |                      ^
      50 |       this.getProjectToken(),
      51 |       false,
      52 |       true,

      at new MixPanelClient (src/services/utility/MixPanelClient.ts:49:22)
      at Object.<anonymous> (src/services/utility/MixPanelClient.ts:107:16)
      at Object.<anonymous> (__tests__/bootstrapTests.ts:1:1)

In my jest setup, the mocking did not solve this issue:

jest.mock('react-native-mixpanel', () => ({
  sharedInstanceWithToken: jest.fn(),
  trackWithProperties: jest.fn(),
}));
    "react-native": "0.62.2",
    "react-native-mixpanel": "^1.2.0",
    "enzyme": "^3.11.0",
    "jest": "^26.4.2",
zzau13 commented 3 years ago

Something like this:

jest.mock('react-native-mixpanel', () => ({
    __esModule: true,
    default: {
        sharedInstanceWithToken: jest.fn(),
        trackWithProperties: jest.fn(),
    }
}))