2017-02-20 53 views
0

我試圖測試一個函數是否在組件的componentDidMount鉤子中調用。React-Native Jest測試函數在componentDidMount中調用

我使用React-Native和Jest來測試我的組件。

組件看起來是這樣的:

const tracker = new GoogleAnalyticsTracker('UA-79731-33'); 
class MyComponent extends Component { 
    componentDidMount() { 
     tracker.trackScreenView(this.props.title); 
    } 
} 

所以我嘲諷GoogleAnalyticsTracker,看起來還好。雖然我不知道如何測試它在componentDidMount掛鉤中被調用。

這是我的測試,它無法正常工作:

import 'react-native'; 
import React from 'react'; 
import renderer from 'react-test-renderer'; 
import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge'; 

import MyComponent from '../'; 

jest.mock('react-native-google-analytics-bridge'); 
const tracker = new GoogleAnalyticsTracker('ABC-123'); 

describe('MyComponent',() => { 
    it('renders',() => { 
     const tree = renderer.create(
      <MyComponent />, 
     ).toJSON(); 
     expect(tree).toMatchSnapshot(); 
     expect(tracker.trackScreenView).toBeCalled(); 
    }); 
}); 

toBeCalled()返回false。

我該如何測試我的功能是否已在componentDidMount中調用?

感謝

回答

0

作出的反應測試僅調用組件的渲染方法,並返回輸出,它並沒有真正啓動組件等所有的生命週期方法不叫。您應該切換到支持組件全部啓動的酶渲染器,使用enzyme.mount

相關問題