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:

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"
],
Similar to alex bennett's answer but global.self could not be referenced in my versions of jest/typescript/node. I'm using:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With