簡體   English   中英

在componentDidMount中調用React-Native Jest測試函數

[英]React-Native Jest test function is called in componentDidMount

我正在嘗試測試是否在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已經調用了我的函數?

謝謝

渲染的react測試僅調用組件的render方法並返回輸出,它並未真正啟動組件,因此未調用所有生命周期方法。 您應該切換到支持使用組件的全面啟動酶渲染enzyme.mount

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM