我想使用 Jest 测试 Angular 组件,而不启动 TestBed。如文档中所述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();
});
});
如果您依赖依赖注入,您应该平衡
TestBed
功能。
service = TestBed.inject(ValueService)
如果您的服务不是 `providedIn:'root',您将需要使用以下命令设置 TestModule:
TestBed.configureTestingModule({providers: [ValueService]});