TESTBED.inject 无法读取 属性 'getComponentFromError' 的 null

TESTBED.inject Cannot read property 'getComponentFromError' of null

我想测试将脚本注入 angular 组件或页面文档的 angular 服务

这是我的服务:

import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable()
export class NgxToolsLoadService {
  constructor(@Inject(DOCUMENT) private document: any) {}

  load(
    src: string,
  ): void {

 let el = this.document.createElement('script');
 el.src=sec;
 this.document.getElementsByTagName('head')[0].appendChild(el);
    
  }
}

这是我的 jest.config

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  onlyChanged: true,
  collectCoverage: false,
  moduleDirectories: ["node_modules", "types"],
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  transform: {
    "^.+\.(t|j)sx?$": "ts-jest",
  },

};

我尝试将 testEnvironment 更改为 jsdom,但出现错误:Exceeded timeout of 5000 ms for a test 并且此代码没有帮助

jest.setTimeout(100000);
jest.useFakeTimers('legacy');

现在我正在使用 testEnvironment: node

然而,这些是我的测试

// myservice.service.spec.ts

import { test, expect, afterAll, beforeEach, jest } from '@jest/globals';
import { TestBed } from '@angular/core/testing';
import { MyService} from './myservice.service';
import { DOCUMENT } from '@angular/common';

let service: MyService;

beforeEach(async () => {
  await TestBed.configureTestingModule({
    providers: [MyService, { provide: Document, useExisting: DOCUMENT }],
  });
  service= TestBed.inject(MyService);
});

test('service should be created', () => {
  expect(ngxToolsLoadService).toBeTruthy();
});

测试失败,无法创建服务 我得到了这个错误

ReferenceError: StaticInjectorError(DynamicTestModule)[NgxToolsLoadService -> InjectionToken DocumentToken]: 
      StaticInjectorError(Platform: core)[NgxToolsLoadService -> InjectionToken DocumentToken]: 
        document is not defined

使用 jest.config.js 文件中的 jest-preset-angular instead of ts-jest 解决