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

查看:129
本文介绍了如何测试使用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文档,了解如何使用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天全站免登陆