3

I want to test Vibration module of react-native, the problem is that I get an error when I try to test it:

With this component:

import React, { useEffect } from 'react';
import { Text, Vibration } from 'react-native';

interface Props {}

export const MyComponent = (props: Props) => {
  useEffect(() => Vibration.vibrate(1), []);
  return (
    <Text>asdaf</Text>
  );
};

And this test file:

// @ts-nocheck
import React from 'react';
import { render } from '@testing-library/react-native';
import { NativeModules } from 'react-native';

import { MyComponent } from '../../../src/modules/MyComponent';

describe('MyComponent', () => {
  it('alpha', () => {
    const { debug } = render(<MyComponent/>);
    expect(true).toBeTruthy();
  });
});

I get this error:

Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'Vibration' could not be found. Verify that a module by this name is registered in the native binary.

I tried to mock react-native like this:

// @ts-nocheck
import React from 'react';
import { render } from '@testing-library/react-native';
import { NativeModules } from 'react-native';

import { ChatRoomContainer } from '../../../src/modules/ChatRoom';

// Mock NativeModules
jest.mock('react-native', () => ({
  ...jest.requireActual('react-native'),
  Vibration: {
    vibrate: jest.fn()
  },
  __esModule: true
}));

describe('MyComponent', () => {
  it('alpha', () => {
    const { debug } = render(<ChatRoomContainer/>);
    expect(true).toBeTruthy();
  });
});

But then I get a ton of warnings related to old modules that should no longer be used:

Warning: CheckBox has been extracted from react-native core and will be removed in a future release. It can now be installed and imported from '@react-native-community/checkbox' instead of 'react-native'. See https://github.com/react-native-community/react-native-checkbox
Warning: DatePickerIOS has been merged with DatePickerAndroid and will be removed in a future release. It can now be installed and imported from '@react-native-community/datetimepicker' instead of 'react-native'. See https://github.com/react-native-community/datetimepicker

What is the best way to test such functionality (like Vibration) of react-native then?

Thanks in advance for you time!

Petro Ivanenko
  • 637
  • 2
  • 8
  • 19

1 Answers1

2

You can mock react-native using the library path, like this:

const mockedVibrate = jest.fn();
jest.mock('react-native/Libraries/Vibration/Vibration', () => ({
  vibrate: mockedVibrate,
}));
Gabriel Santos
  • 302
  • 1
  • 11