gpt4 book ai didi

javascript - 空注入(inject)器错误 : StaticInjectorError(DynamicTestModule) When Testing in Angular 2

转载 作者:行者123 更新时间:2023-11-30 14:08:17 28 4
gpt4 key购买 nike

我是 Angular2 的新手,正在尝试在 app.component.spec.ts 文件中编写测试。我的应用程序相对简单,除了它从第 3 方库(由同事编写)导入 LoginComponent 和 LogoutComponent。这些组件现在分别用于路由登录或注销,非常简单的东西。运行 ng serve 编译正常,应用程序运行“顺利”。但是,运行 ng test 会出现此错误:

NullInjectorError: StaticInjectorError(DynamicTestModule)[LogoutComponent -> SessionService]: 
StaticInjectorError(Platform: core)[LogoutComponent -> SessionService]:
NullInjectorError: No provider for SessionService!

LogoutComponent 是从另一个项目导入的。此错误是否意味着我需要进入该项目并进行一些更改,或者我是否应该以某种方式在我的项目中模拟 SessionService?

具体代码:

import {} from 'jasmine';
import {async, TestBed} from '@angular/core/testing';
import {RouterTestingModule} from '@angular/router/testing';
import {AuthErrorStateService, LogoutComponent} from '@custom-library';

import {AppComponent} from './app.component';
import {AppErrorStateService} from './core/error-states/app-error-state.service';
import {TopNavComponent} from './core/top-nav/top-nav.component';

describe('AppComponent', () => {
beforeEach(async(() => {
TestBed
.configureTestingModule({
imports: [RouterTestingModule],
providers: [
AppErrorStateService, AuthErrorStateService
],
declarations: [AppComponent, TopNavComponent, LogoutComponent],
})
.compileComponents();
}));

it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});

it(`should have as title 'My App'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('My App');
});

it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toEqual('Welcome to My App!');
});
});

最佳答案

问题是像这样在 TestBed 中声明多个组件

 declarations: [AppComponent, TopNavComponent, LogoutComponent]

导致在测试调用 compileComponents() 时实例化多个组件。发生这种情况时,declarations 数组中的每个组件都需要在 providers 数组中声明其依赖项才能完成实例化。声明的组件之一依赖于 SessionService,但提供者中不存在该服务,因此您会收到 NullInjectorError

有两种解决方法:

  • declarations数组中只声明一个组件并添加schemas: [ CUSTOM_ELEMENTS_SCHEMA ]TestBed 配置对象
  • 继续声明多个组件并添加所有每个组件的依赖项(或其模拟)providers 数组

关于javascript - 空注入(inject)器错误 : StaticInjectorError(DynamicTestModule) When Testing in Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54952009/

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