Search code examples
javascriptreact-nativejestjs

How to test a library React Native using Jest


I'm trying to test a React Native library using Jest, but it shows an error.

Here my function code:

export const createChannel = (): void => {
  PushNotification.createChannel({
    channelId: 'test-channel',
    channelName: 'Test Channel',
    vibrate: true,
  });
};

I'm using react-native-push-notification library to this function.

And here's my testing code:

import PushNotification from 'react-native-push-notification';
import {createChannel} from '../src/functions/PomodoroFunction';
jest.mock('react-native-push-notification', () => 'PushNotification.createChannel');

describe('Create Channel unit test', () => {
    it('Should be called',()=>{
      const mockFN = createChannel()
      expect(mockFN).toHaveBeenCalled();
    })
  });

Error shown:

TypeError: _reactNativePushNotification.default.createChannel is not a function

What can I try next?


Solution

  • Try

    import * as PushNotification from 'react-native-push-notification';
    ...
    const create = jest.fn();
    const rnpn = jest.spyOn(PushNotification, 'default').mockImplementation(() => {
      return { createChannel: create } as any;
    });
    ...
    

    And then use create in your test. I'm not sure what you're testing in the test above, but this is a good way to mock functions you don't want to run on your test.