Applicationinsights-js: AppInsightsModule.js is blocking my ability to mock for unit testing (using Jest).

Created on 22 Jun 2017  路  25Comments  路  Source: microsoft/ApplicationInsights-JS

Hi there,

I am trying to set up jest for my application built using React. I am using ApplicationInsights-js however, whenever I try to run my tests, I keep getting "define is undefined" on any of my tests using components that import ApplicationInsights.

We are using the current version (1.0.9) and the only solution that I have come up with was to comment out the define() function.

Thanks!

bug

Most helpful comment

If you're using jest, adding an empty applicationinsights-js.js file to your __mocks__ folder fixes this issue. If you need to mock the applicationinsights-js functionality, you should be able to do that here as well. Please note that __mocks__ is case-sensitive. For more info about jest mocks, see Jest Mock documentation

All 25 comments

This was fixed in #486 and will be released in v1.0.10 later this week.

@KamilSzostak I still get this in v1.0.11. Our previously working karma-webpack suite has suddenly started breaking.

Chrome 60.0.3112 (Windows 10 0.0.0) ERROR
  Uncaught ReferenceError: define is not defined
  at c:/Users/Legogris/AppData/Local/node_modules/appinsights-usage/node_modules/applicationinsights-js/JavaScript/JavaScriptSDK.Module/AppInsightsModule.js:3:0 <- C:/Users/Legogris/AppData/Local/Temp/dfd5f13d536b17db07dd36f42a19f81e.browserify:23038

Other users are also reporting this #518.

@KamilSzostak any update on when this will be fixed? or how it could be temporarily silenced for now?

I am experiencing the same issue here. Could the solution be to switch to commonjs?

define("JavaScriptSDK.Module/AppInsightsModule", ["require", "exports"], function (require, exports) {
^
ReferenceError: define is not defined

tbh, not beeing able to run tests with this module is a show stopper. Anyone got a workaround for this? I am running tests like this:

"test": "cross-env NODE_ENV=test mocha --reporter=min --no-colors --compilers js:babel-core/register --require babel-polyfill --require ignore-styles --require jsdom-global/register \"tools/**/*.spec.js\" \"src/**/*.spec.js\" \"cfg/**/*.spec.js\"",

I've tried using amdefine, with no success:

 --require amdefine/intercept

Resulting in:

SyntaxError: Identifier 'define' has already been declared

Got a workaround for this:

Create a helper with global definition

/*eslint-env node, mocha */
global.define = () => {};

Use it in script:

"test": "cross-env NODE_ENV=test mocha --reporter=min --no-colors --compilers js:babel-core/register --require babel-polyfill --require ignore-styles --require jsdom-global/register \"test/helper.js\" \"tools/**/*.spec.js\" \"src/**/*.spec.js\" \"cfg/**/*.spec.js\"",

For jest, you can add:

 "setupFiles": ["<rootDir>/jest/disableAppInsights.js"],

to your Jest configuration file, and then create a file by following @phun-ky'method.

This is also an issue using karma in an angular project. Can someone look into it please.

"applicationinsights-js": "1.0.14", "jest": "^22.1.4", "ts-jest": "^22.0.1",

Error: ReferenceError: define is not defined at Object.<anonymous> (node_modules/applicationinsights-js/bundle/ai.module.js:178:1)

Will try the workaround, please fix

+1, I'm running into this error with applicationinsights-js 1.0.15 used in TypeScript, though I'm not using Jest. Is there an ETA on the fix?

I'm not sure how to workaround this from the TypeScript context. Please advise.

package.json (trimmed)

"devDependencies": {
        "@types/applicationinsights-js": "^1.0.5"
    }
"dependencies": {
        "applicationinsights-js": "^1.0.15"
    }

Usage

import { AppInsights } from 'applicationinsights-js';

AppInsights.config.instrumentationKey = 'my key';
AppInsights.trackTrace('my message');

Still seeing this issue: I'm using Angular 5, Jest and the microsoft-applicationinsights-angular5 but it references back to the JS. It all workd prefect in the app but can't make it work in my unit tests. Does anyone have a solution?

If you're using jest, adding an empty applicationinsights-js.js file to your __mocks__ folder fixes this issue. If you need to mock the applicationinsights-js functionality, you should be able to do that here as well. Please note that __mocks__ is case-sensitive. For more info about jest mocks, see Jest Mock documentation

I'm having the same issue. (applicationinsights-js v1.0.18) I've added the empty file and that error is gone. But now the following error is shown when running the tests: 'Cannot read property 'startTrackPage' of undefined'.

What do I have to do to fix this error?

Adding the empty file gives me a cannot read 'config' of undefined problem. What do we do to fix this??

What my colleague did to solve the problem in a quick hack way was to wrap the AppInsights commands affect in an if (AppInsights !== undefined) this got our unit tests back up and working again.

I have created a wrapper around the library as a workaround. Now I can mock the wrapper functions. It is not the best solution... but it works :-)

You can also use babel-plugin-transform-amd-to-commonjs to transpile Application Insights to CommonJS upon import. Here is a little project using Jest as an example.

Related issue: Support for CommonJS #301

In Jest there is the moduleNameMapper configuration that can resolve this.

{
  "moduleNameMapper": {
    "applicationinsights-js": "<rootDir>/myFakeAppInsights"
  }
}

Then in myFakeAppInsights (ts or js) export the methods you are using:

export class AppInsights {
  static downloadAndConfig() {}
}

This is also happening when trying to integrate with Angular applications as well.
Here it is happening within Stackblitz example: https://stackblitz.com/edit/angular-kazq2e?file=src%2Fapp%2Fapp.module.ts

I am using create-react-app with typescript.
My npm was this:
"ci-test": "cross-env CI=true react-scripts-ts test --env=jsdom --reporters=jest-junit --coverage"

The combination of @adeogunsamuel 's suggestion and @barrymichaeldoyle 's suggestion is what worked for me. Thank you!

This packaging/transpilation problem should be solved by ApplicationInsights SDK v1.0, which is now still in beta and can be installed issuing npm i --save @microsoft/applicationinsights-web.

If you're using React you might also find useful react-appinsights, whose v3.x (in beta too) supports ApplicationInsights SDK v1.0: npm install --save react-appinsights@beta. Docs of the beta version are currently in the typescript-rewrite branch.

I was able to solve this by adding in your jest config add 'applicationinsights-js': '<rootDir>/test/app-test-insights.js',

then in app-test-insights.js add
export const AppInsights = new Proxy({}, { get: () => () => { }, });

You need to mock appinsights at the highest possible level you use it, in my case, it is the react wrapper withTracking method:

jest.mock('react-appinsights', () => ({ default: { withTracking: jest.fn() }, }));

"react-appinsights": "^2.0.2"

The versions 1.0.x of the SDK only allow AMD consumers to work. Version 2.0.x-beta (in beta currently, latest public version is 1.0.0-beta-12) supports UMD (if you look in the npm package, we drop distributables in the following formats):

/browser: intended to be used for browser (UMD)
/dist: intended for nodejs (commonjs format)
/ESM: future looking
/src: source code if you want to compile in your build system

Please try this out to see if issue still persists.

In Jest there is the moduleNameMapper configuration that can resolve this.

{
  "moduleNameMapper": {
    "applicationinsights-js": "<rootDir>/myFakeAppInsights"
  }
}

Then in myFakeAppInsights (ts or js) export the methods you are using:

export class AppInsights {
  static downloadAndConfig() {}
}

To be added, the function is called downloadAndSetup(). At least in my latest version

 export class AppInsights {
  static downloadAndSetup() {}
}
Was this page helpful?
0 / 5 - 0 ratings