4

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"
],
skyboyer
  • 22,209
  • 7
  • 57
  • 64
DauleDK
  • 3,313
  • 11
  • 55
  • 98

2 Answers2

3

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

2

I experienced this today as well. In your setupTests file, or any other place Jest let's you do set up test configuration, add the following:

const crypto = require('crypto')

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

You may even be able to add this to your test file but not sure how your project is configured. Hope this helps. (Since you're using .ts and angular, you may also have to hack your way around some types for this).

alex bennett
  • 794
  • 1
  • 10
  • 17