Petro Ivanenko
Petro Ivanenko

Reputation: 727

How to test react-native methods?

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!

Upvotes: 3

Views: 762

Answers (1)

Gabriel Ferreira
Gabriel Ferreira

Reputation: 351

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

const mockedVibrate = jest.fn();
jest.mock('react-native/Libraries/Vibration/Vibration', () => ({
   vibrate: mockedVibrate,
}));

Upvotes: 3

Related Questions