首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何测试react-native方法?

如何测试react-native方法?
EN

Stack Overflow用户
提问于 2021-01-22 23:44:47
回答 1查看 199关注 0票数 2

我想测试react-nativeVibration模块,问题是当我尝试测试它时,我得到了一个错误:

使用此组件:

代码语言:javascript
复制
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>
  );
};

这个测试文件:

代码语言:javascript
复制
// @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();
  });
});

我得到了这个错误:

代码语言:javascript
复制
Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'Vibration' could not be found. Verify that a module by this name is registered in the native binary.

我试着这样模拟react-native

代码语言:javascript
复制
// @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();
  });
});

但是,我收到了大量与旧模块相关的警告,这些模块不应该再使用了:

代码语言:javascript
复制
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

那么,测试react-native的此类功能(如Vibration)的最佳方式是什么?

提前感谢您的宝贵时间!

EN

回答 1

Stack Overflow用户

发布于 2021-07-20 08:00:10

您可以使用库路径模拟react-native,如下所示:

代码语言:javascript
复制
const mockedVibrate = jest.fn();
jest.mock('react-native/Libraries/Vibration/Vibration', () => ({
  vibrate: mockedVibrate,
}));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65848268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档