如何使用 Jest 测试导入自定义本机模块的 React Native 组件? [英] How to test a React Native component that imports a custom native module with Jest?

查看:35
本文介绍了如何使用 Jest 测试导入自定义本机模块的 React Native 组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我尝试使用 React Native 0.39 和 Jest 18 测试的一个简单组件:

Here is a simple component that I am trying to test using React Native 0.39 and Jest 18:

// index.ios.js

import React, { Component } from 'react';
import { AppRegistry, NativeModules, View } from 'react-native';

export default class TestProject extends Component {
  componentDidMount() {
    NativeModules.TestModule.test();
  }

  render() {
    return <View style={{ flex: 1 }} />;
  }
}

AppRegistry.registerComponent('TestProject', () => TestProject);

这是 TestModule 和它的 test 方法:

Here is TestModule and its test method:

// ios/TestProject/TestModule.m

#import "TestModule.h"

@implementation TestModule

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(test){
  NSLog(@"This is a test");
}

@end

以下测试失败并出现错误 TypeError: Cannot read property 'test' of undefined:

The following test fails with the error TypeError: Cannot read property 'test' of undefined:

// __tests__/index.ios.js

import 'react-native';
import renderer from 'react-test-renderer';
import React from 'react';
import Index from '../index.ios.js';

it('renders correctly', () => {
  const tree = renderer.create(
    <Index />
  );
});

我已经阅读了关于如何使用 jest.mock 模拟本机模块,但我仍然不清楚如何扩展 Jest 的 NativeModules 模拟以包含我上面的 TestModule 类.

I have read the Jest docs on how to Mock native modules using jest.mock, but am still unclear as to how to extend Jest's mock of NativeModules to include my TestModule class above.

推荐答案

您可以简单地在您的本机模块所在的位置添加一个模拟:

You can simply add a mock where your native module should be:

import {
  NativeModules,
} from 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';

describe('TestProject', () => {
  beforeEach(() => {
    NativeModules.TestModule = { test: jest.fn() } 
  });
  ...
});

这篇关于如何使用 Jest 测试导入自定义本机模块的 React Native 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆