我的目标是使用 powerbi-client在我的 Angular 9 应用程序中。我的 POC 组件运行良好,使用这样的库:
import * as pbi from 'powerbi-client'; // It's installad in package.json
但是,当我使用 jest 运行单元测试时,出现此错误:
TypeError: Cannot read property 'getRandomValues' of undefined
它看起来像这样:
非常欢迎任何帮助🤷🏽♂️
我尝试在
angular.json
的脚本部分下添加库,但这没有帮助:"scripts": [
"./node_modules/powerbi-client/dist/powerbi.min.js"
],
最佳答案
类似于亚历克斯贝内特的回答,但 global.self
无法在我的 jest/typescript/node 版本中引用。我正在使用:
所以我修改了
setupJest.ts
在我的 Angular 9 应用程序的根目录中添加以下内容:const crypto = require('crypto')
declare var window: Window & typeof globalThis;
Object.defineProperty(window.self, 'crypto', {
value: {
getRandomValues: (arr) => crypto.randomBytes(arr.length)
}
});
window 的声明是 powerbi-client 如何声明它的逐行副本(在 node_modules/powerbi-client/dist/powerbi.js - 搜索 getRandomValues
然后按照对 window
的引用进行操作)。问题似乎源于 jsDom 没有实现来自
window
的所有方法.按:Jest's Documentation
关于angular - 如何在 Angular 应用程序中使用 powerbi-client 依赖项,而不破坏 Jest 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60392102/