React 应用程序 Jest 单元测试因 Microsoft 应用程序洞察反应插件而失败

问题描述 投票:0回答:1

我正在尝试在我的 React 应用程序中使用 Microsoft 的 Application Insights JavaScript SDK React 插件,尽管它工作成功,但我在通过 Jest 和 Enzyme 单元测试时遇到了困难。

我已经设置了如下的单元测试:

import React from 'react';
import {act} from 'react-dom/test-utils';
import ReactDOM from 'react-dom';
import App from '../App.view';

jest.mock('@microsoft/applicationinsights-react-js', () => ({
  ReactPlugin: Object,
}));

jest.mock('@microsoft/applicationinsights-web', () => ({
  ApplicationInsights: Object,
  loadAppInsights: () => ({}),
}));

describe('App View', () => {
  it('renders without crashing', () => {
    const div = document.createElement('div');
    act(() => {
      ReactDOM.render(<App />, div);
    });
    ReactDOM.unmountComponentAtNode(div);
  });
});

我的应用程序洞察服务为:

import {ApplicationInsights} from '@microsoft/applicationinsights-web';
import {ReactPlugin, withAITracking} from '@microsoft/applicationinsights-react-js';
import {createBrowserHistory} from 'history';

// Set up AppInsights connection
const browserHistory = createBrowserHistory({basename: ''});
const reactPlugin = new ReactPlugin();
const ai = new ApplicationInsights({
  config: {
    instrumentationKey:
      process.env.REACT_APP_APPINSIGHTS_KEY || 'xxxxxxxxxxx-xxxxxxxxxx-xxxxxxx-xxxxx',
    extensions: [reactPlugin],
    extensionConfig: {
      [reactPlugin.identifier]: {history: browserHistory},
    },
  },
});
ai.loadAppInsights();

export default Component => withAITracking(reactPlugin, Component);
export const appInsights = ai.appInsights;

当我运行测试时,我不断收到错误,

TypeError: ai.loadAppInsights is not a function

由于我对应用程序洞察模块使用玩笑模拟,因此我也尝试以多种方式模拟此方法,但没有成功。关于我在这里缺少什么有什么想法吗?我也无法找到任何关于如何将应用程序洞察正确集成到 React 应用程序中的良好文档,其中包括正确的单元测试。

提前致谢!

javascript reactjs unit-testing jestjs azure-application-insights
1个回答
0
投票

我尝试了这个模拟,它正在工作,

jest.mock('@microsoft/applicationinsights-web', () => ({
  ApplicationInsights: jest.fn().mockImplementation(() => ({
    loadAppInsights: jest.fn(),
    addTelemetryInitializer: jest.fn(),
    trackPageView: jest.fn(),
    trackException: jest.fn(),
    trackTrace: jest.fn(),
    trackEvent: jest.fn(),
    flush: jest.fn(),
    startTrackPage: jest.fn(),
    stopTrackPage: jest.fn(),
  })),
}));
© www.soinside.com 2019 - 2024. All rights reserved.