使用Jest和inject()函数进行角度测试

问题描述 投票:0回答:2

我想使用 Jest 测试 Angular 组件,而不启动 TestBed。如果可能的话,我想在没有 Angular 上下文的情况下进行纯 JavaScript 测试。如文档中所述https://angular.io/guide/testing-services#testing-services

describe('ValueService', () => {
  let service: ValueService;
  beforeEach(() => {
    service = new ValueService();
  });

  test('#getValue should return real value', () => {
    expect(service.getValue()).toBe('real value');
  });

如果组件或服务使用

{ inject} from '@angular/core'
,则不起作用。

export class ValueService () { 
  protected destroyRef: DestroyRef = inject(DestroyRef);
  [...]
}

在这种情况下我得到了这个错误:

Error: NG0203: inject() must be called from an injection context such as a constructor, 
factory function, field initialiser, or a function used with `runInInjectionContext'.
 See https://angular.io/errors/NG0203 for more information.

是否可以在测试期间禁用角度 DI?或模拟注入()行为?

我也在尝试使用

runInInjectionContext
的另一种方法,但我还没有找到一种方法来模拟所有提供者。 .

  beforeEach(() => {
    runInInjectionContext(Injector.create({ providers: [{ provide: any, useValue: jest.mock }] }), () => {
      service = new ValueService();
    });
  });
angular dependency-injection jestjs
2个回答
0
投票

如果您依赖依赖注入,您应该平衡

TestBed
功能。

service = TestBed.inject(ValueService)

如果您的服务不是 `providedIn:'root',您将需要使用以下命令设置 TestModule:

TestBed.configureTestingModule({providers: [ValueService]});  

-1
投票

使用

jest.mock('@angular/core');
让我模拟角度分量的 DI。模拟条件必须在describe(...)之前定义。

jest.mock('@angular/core');

describe('ValueService', () => {
  let service: ValueService;
  beforeEach(() => {
    service = new ValueService();
  });

  test('#getValue should return real value', () => {
    expect(service.getValue()).toBe('real value');
  });

© www.soinside.com 2019 - 2024. All rights reserved.