gpt4 book ai didi

angular - 如何在 Angular 应用程序中使用 powerbi-client 依赖项,而不破坏 Jest 测试?

转载 作者:行者123 更新时间:2023-12-02 04:20:24 24 4
gpt4 key购买 nike

我的目标是使用 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

它看起来像这样:
enter image description here

非常欢迎任何帮助🤷🏽‍♂️

我尝试在 angular.json 的脚本部分下添加库,但这没有帮助:
"scripts": [
"./node_modules/powerbi-client/dist/powerbi.min.js"
],

最佳答案

类似于亚历克斯贝内特的回答,但 global.self无法在我的 jest/typescript/node 版本中引用。我正在使用:

  • jest 版本 24.9.0 (@types/jest v24.0.23) 带有 jest-preset-angular v8.2.1、ts-jest v24.2.0。
  • typescript 3.7.5 (ts-node v8.10.2)
  • @types/node 版本 14.0.24
  • powerbi 客户端:2.11.0

  • 所以我修改了 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com