2017-02-20 80 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

相关问题