1

我正在使用react-native-fcmjest來測試我的React Native應用程序。我有一個非常基本的測試,它看起來像這樣:React Native jest test:TypeError:無法讀取未定義的屬性'unsubscribeFromTopic'

import 'react-native'; 
import React from 'react'; 
import PushController from '../app/PushController'; 
// Note: test renderer must be required after react-native. 
import renderer from 'react-test-renderer'; 

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

而且PushController是有點大,所以這裏的有趣的部分

import React, { Component } from 'react'; 
import { AsyncStorage } from 'react-native'; 
import FCM from 'react-native-fcm'; 

export default class PushController extends Component { 
(...) 

    componentDidMount() { 
    if (this.notificationListener) this.notificationListener.remove(); 

    this.notificationListener = FCM.on('notification', (notif) => { 

     if (!notif.local_notification) { 
      this.notifyUser(notif.coffee); 
     } 

    }); 
    FCM.unsubscribeFromTopic('/topics/coffee'); 
    FCM.subscribeToTopic('/topics/coffee'); 
    } 
(...) 

但是,在運行測試時,我得到

__tests__/PushControllerTest.js 
    ● works correctly 

    TypeError: Cannot read property 'unsubscribeFromTopic' of undefined 

     at Object.FCM.unsubscribeFromTopic (node_modules/react-native-fcm/index.js:86:15) 
     at PushController.componentDidMount (app/PushController.js:44:26) 
     at node_modules/react-test-renderer/lib/ReactCompositeComponent.js:265:25 
     at measureLifeCyclePerf (node_modules/react-test-renderer/lib/ReactCompositeComponent.js:75:12) 
     at node_modules/react-test-renderer/lib/ReactCompositeComponent.js:264:11 
     at CallbackQueue.notifyAll (node_modules/react-test-renderer/lib/CallbackQueue.js:76:22) 
     at ReactTestReconcileTransaction.ON_DOM_READY_QUEUEING.close (node_modules/react-test-renderer/lib/ReactTestReconcileTransaction.js:36:26) 
     at ReactTestReconcileTransaction.TransactionImpl.closeAll (node_modules/react-test-renderer/lib/Transaction.js:206:25) 
     at ReactTestReconcileTransaction.TransactionImpl.perform (node_modules/react-test-renderer/lib/Transaction.js:153:16) 
     at batchedMountComponentIntoNode (node_modules/react-test-renderer/lib/ReactTestMount.js:69:27) 

我試過在測試中包含很多東西,比如jest.mock('react-native-fcm')和其他東西,但是我根本無法完成它。我得到jest自動嘲笑圖書館,但我不明白爲什麼FCM是未定義的。有任何想法嗎?

回答

3

我設法解決它,最後!只要需要我的測試變爲

import 'react-native'; 
import React from 'react'; 
import PushController from '../app/PushController'; 
// Note: test renderer must be required after react-native. 
import renderer from 'react-test-renderer'; 
import FCM from 'react-native-fcm'; // <-- This 

it('works correctly',() => { 
    FCM.unsubscribeFromTopic = jest.fn(); // <-- These two 
    FCM.subscribeToTopic = jest.fn(); 
    const tree = renderer.create(
    <PushController /> 
); 
}); 

要確保實際調用嘲笑。我之前做過很多的谷歌搜索,所以我相信這對別人很有用。

相關問題