[英]React-Native Jest test function is called in componentDidMount
I'm trying to test if a function is called in the componentDidMount
hook of my component. 我正在尝试测试是否在componentDidMount
挂钩中调用了函数。
I use React-Native and Jest to test my component. 我使用React-Native和Jest测试我的组件。
The component looks like this: 该组件如下所示:
const tracker = new GoogleAnalyticsTracker('UA-79731-33');
class MyComponent extends Component {
componentDidMount() {
tracker.trackScreenView(this.props.title);
}
}
So I'm mocking the GoogleAnalyticsTracker
, it looks okay. 所以我在模仿GoogleAnalyticsTracker
,看起来还不错。 Although I'm not sure how I can test that it has been called in the componentDidMount
hook. 尽管我不确定如何才能在componentDidMount
挂钩中测试它是否已被调用。
This is my test, which doesn't work: 这是我的测试,不起作用:
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();
});
});
The toBeCalled()
returns false. toBeCalled()
返回false。
How can I test that my function has been called in the componentDidMount
? 如何测试在componentDidMount
已经调用了我的函数?
Thanks 谢谢
The react test rendered only calls the render method of a component and returns the output, it does not really start the component and so all the life cycle methods are not called. 渲染的react测试仅调用组件的render方法并返回输出,它并未真正启动组件,因此未调用所有生命周期方法。 You should switch to the enzyme renderer which supports the full start of components using enzyme.mount
您应该切换到支持使用组件的全面启动酶渲染enzyme.mount
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.