question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

TypeError: appInsights.loadAppInsights is not a function Jest React 18

See original GitHub issue

Hi! I’m trying to create test cases for my modules and when I need to mock app applicationinsights-web i’m getting TypeError: appInsights.loadAppInsights is not a function

My test:


jest.mock('@microsoft/applicationinsights-web');

describe('Example | ', function () {
	test('Renders Example paragraph', () => {
		render(
			<Home />);
		const linkElement = screen.getByText(/Home/i);
		expect(linkElement).toBeInTheDocument();
	});
});

My component:

function Home() {	
	const generateException = () => {
		trackException(' Exception UI Test ');
	};
	const generateTrace = () => {
		trackTrace(' Trace UI Test ');
	};
	const generateEvent = () => {
		trackEvent(' Event UI Test ');
	};
	return (
		<Container maxWidth="sm">
			<Box sx={{ my: 4 }}>
				<Typography variant="h4" component="h1" gutterBottom> Home </Typography>
			</Box>
			<Box sx={{ my: 1 }}>
				<Button variant="contained" onClick={generateException}>Exception Test</Button>
			</Box>
			<Box sx={{ my: 1 }}>
				<Button variant="contained" onClick={generateTrace}>Trace Test</Button>
			</Box>
			<Box sx={{ my: 1 }}>
				<Button variant="contained" onClick={generateEvent}>Event Test</Button>
			</Box>
		</Container>
	);
}

My Telemetry service

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

const reactPlugin = new ReactPlugin();

const appInsights = new ApplicationInsights({
	config: {
		connectionString: process.env.REACT_APP_APPINSIGHTS_CONNECTION,
		extensions: [reactPlugin],
		extensionConfig: {},
		enableAutoRouteTracking: true,
		disableAjaxTracking: false,
		autoTrackPageVisitTime: true,
		enableCorsCorrelation: true,
		enableRequestHeaderTracking: true,
		enableResponseHeaderTracking: true
	}
});
appInsights.loadAppInsights();

appInsights.addTelemetryInitializer((env:ITelemetryItem) => {
	env.tags = env.tags || [];
	env.tags['ai.cloud.role'] = 'testTag';
});`

My App:


import { AppInsightsContext } from '@microsoft/applicationinsights-react-js';
import { reactPlugin } from './shared/appInsights/TelemetryService';

function App() {
	
	return (
		<BrowserRouter>
			<AppInsightsContext.Provider value={reactPlugin}>
				<div className="App">
					<Routes>
						<Route path="/" element={<Home/>} />
						<Route path="/home" element={<Home/>} />
					</Routes>
					<Footer/>
				</div>
			</AppInsightsContext.Provider>
		</BrowserRouter>
	);
}

Stack:

    "dotenv": "^16.0.3",
    "jest": "^28.1.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router": "^6.4.3",
    "react-router-dom": "^6.4.3",
    "react-scripts": "5.0.1",
    "@microsoft/applicationinsights-react-js": "^3.4.0",
    "@microsoft/applicationinsights-web": "^2.8.9",

Any advice on this one? Thanks!

Issue Analytics

  • State:open
  • Created 10 months ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
MSNevcommented, Nov 10, 2022

Oh, nice! In that case if you mocking everything then, you might also be able to simply either

  • pass a valid looking instrumentationKey or
  • pass an invalid value (we use values like “testiKey”) and also include disableInstrumentationKeyValidation as true so that the SDK will still attempt to initialize.
1reaction
MSNevcommented, Nov 9, 2022

Yes, this is a “side-effect” of how we are creating the class for better minification in the browser. There are several options but the easiest way it to simply “create” an instance of the class just prior to setting up the mock. As the “prototype” level functions don’t exist until that first instance is created.

Read more comments on GitHub >

github_iconTop Results From Across the Web

React app Jest unit test failing with Microsoft application ...
appInsights ;. When I run my tests, I keep getting the error, TypeError: ai.loadAppInsights is not a function. Since I'm using jest mocking ......
Read more >
@microsoft/applicationinsights-core-js - Package Manager
Fast, reliable, and secure dependency management.
Read more >
React plug-in for Application Insights JavaScript SDK
Learn how to install and use the React plug-in for the Application Insights JavaScript SDK.
Read more >
Implementing Monitoring in React Using AppInsights
Part 1 - Getting Started with Monitoring React Applications (this post) ... and really only focused on traffic sources, not true monitoring.
Read more >
Writing tests: type error not a function - JavaScript
Hi, It is my first time writing tests, using jest. The error says that sortEvents is not a function even though it is:...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found