Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use powerbi-client dependency in Angular application, without breaking jest tests?

My goal is to use powerbi-client in my Angular 9 application. My POC component works great, using the library like this:

import * as pbi from 'powerbi-client'; // It's installad in package.json

However, when I run my unit tests with jest, I get this error:

TypeError: Cannot read property 'getRandomValues' of undefined

It looks like this: enter image description here

Any help is very welcome 🤷🏽‍♂️

I tried adding the library under the script section of angular.json, but this did not help:

"scripts": [
    "./node_modules/powerbi-client/dist/powerbi.min.js"
],
like image 679
DauleDK Avatar asked Oct 29 '25 02:10

DauleDK


1 Answers

Similar to alex bennett's answer but global.self could not be referenced in my versions of jest/typescript/node. I'm using:

  • jest version 24.9.0 (@types/jest v24.0.23) with jest-preset-angular v8.2.1, ts-jest v24.2.0.
  • typescript 3.7.5 (ts-node v8.10.2)
  • @types/node version 14.0.24
  • powerbi-client: 2.11.0

So I modified setupJest.ts in the root of my Angular 9 application to the following:

const crypto = require('crypto')
declare var window: Window & typeof globalThis;

Object.defineProperty(window.self, 'crypto', {
  value: {
    getRandomValues: (arr) => crypto.randomBytes(arr.length)
  }
});

The declaration of window is a line-for-line copy of how powerbi-client declares it(in node_modules/powerbi-client/dist/powerbi.js - search for getRandomValues and then follow the reference to window).

The problem seems to stem from jsDom not implementing all methods from window. As per: Jest's Documentation

like image 109
Andrew Glenn Avatar answered Oct 30 '25 18:10

Andrew Glenn