在Angular 7中,如果在ngOnInit方法中进行依赖注入的单元测试时出现问题,可能是因为在测试过程中没有正确配置测试环境。以下是一个解决方法的示例:
首先,确保你的组件被正确导入:
import { MyComponent } from './my.component';
然后,在describe块中配置测试环境:
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
在上述代码中,我们使用TestBed来配置测试环境,并使用compileComponents()方法编译组件。然后,我们使用createComponent方法创建组件实例,并进行必要的变更检测。
接下来,我们可以在beforeEach块中设置依赖注入:
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { MyComponent } from './my.component';
import { MyService } from './my.service';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
let myService: MyService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: [ MyService ] // 添加服务提供商
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
myService = TestBed.get(MyService); // 获取注入的服务实例
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call ngOnInit and inject MyService', () => {
spyOn(component, 'ngOnInit').and.callThrough();
expect(component.ngOnInit).toHaveBeenCalled();
expect(myService).toBeTruthy();
});
});
在上述代码中,我们首先在providers数组中添加MyService,以便在组件实例化时注入该服务。然后,我们使用TestBed的get方法获取MyService实例,并将其存储在myService变量中。
接下来,在it块中,我们使用spyOn方法来监视ngOnInit方法,并验证它是否被调用。我们还验证myService是否成功注入。
这样,我们就可以在ngOnInit方法中进行依赖注入的单元测试了。