Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

jestjs - 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!

question from:https://stackoverflow.com/questions/65848268/how-to-test-react-native-methods

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...