mixpanel / mixpanel-react-native

Official React Native Tracking Library for Mixpanel Analytics
https://mixpanel.com
Apache License 2.0
108 stars 48 forks source link

Feature Request: Mixpanel Mock Object #133

Open ConorCorp opened 2 years ago

ConorCorp commented 2 years ago

I would love to see an importable mixpanel mock to use in unit testing.

My current solution:

From another closed issue:

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

Suggested Solution:

Something like 'react-native-permissions/mock' but in typescript. Which imports into the setup.tsx file for jest like so:

import mockRnPerms from 'react-native-permissions/mock';

// Mocking react permissions

jest.mock('react-native-permissions', () => {
  return mockRnPerms;
});
RadicalRoy commented 2 years ago

Thanks @ConorCorp . Used this in our jest.setup file

jest.mock('mixpanel-react-native', () => ({
  __esModule: true,
  default: () => jest.fn(),
  Mixpanel: jest.fn(() => ({
    init: jest.fn(),
    getPeople: () => ({ set: jest.fn() }),
    reset: jest.fn(),
  })),
}));
miso-belica commented 1 year ago

While mocking manually is an option when the library changes the API we always spend time to debug tests until we find out our mock needs an update. I think the best would be if we could do in setupFilesAfterEnv: ['./jest.setup.js'] file the following:

import mixpanelMock from 'mixpanel-react-native/mock';
// or if also support web in our react-native app
import mixpanelMock from 'mixpanel-browser/mock';

jest.mock('mixpanel-react-native', () => mixpanelMock);

Some libraries go as far as import '@shopify/flash-list/jestSetup' but that limits them to Jest. With the above approach I can use any mocking library. Also, when the library changes API the mock is always up to date.

Since Mixpanel is only "logging" library maybe it would be enough if it works in tests without any token or with some special token when it sends nothing to the Mixpanel server and returns empty collections where needed. WDYT?

PieterT2000 commented 2 weeks ago

+1, highly needed