這裏是我試圖用反應測試一個簡單的組件原生0.39和玩笑18:如何測試使用Jest導入自定義本地模塊的React Native組件?
// 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
方法:
// 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
:
// __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 />
);
});
我已經閱讀如何Mock native modules using jest.mock的玩笑文檔,但我ST不知道如何擴展Jest的NativeModules模擬以包含上面的TestModule類。
謝謝!傳遞給'beforeEach'的函數缺少一個閉合大括號,但除此之外就像一個魅力。我也選擇使用'beforeAll',因爲這個設置只需要運行一次,而不是在每個規範之前運行。 – andybangs
太棒了,我添加了缺少的大括號。 – rgoldfinger