我对Angular很新。
在了解框架如何运作后,我正在查看测试。
我发现一个使用服务的组件,如果该服务使用HttpModule,组件测试规范文件也需要导入HttpModule。我真的不明白背后的概念。
我认为使用该模块的组件不需要知道服务是如何工作的,因为它是服务执行的一种封装过程。更改不改变api的服务也不应该破坏组件。
如果我的理解是正确的,那么如果有一个组件在开发的最初阶段没有使用HttpModule,那么有人会在该服务上编写一个组件,并且两个开发人员都会编写测试。有一天,服务开发人员决定使用HttpModule,但组件开发人员可能不知道,在这种情况下,组件的测试将失败。
为什么我们需要将HttpModule放入组件规范文件中?
编辑: 示例如下
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { UserComponent } from './user.component';
import { DataService } from '../../services/data.service';
describe('UserComponent', () => {
let component: UserComponent;
let fixture: ComponentFixture<UserComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ UserComponent ],
imports: [
FormsModule,
HttpModule, // this line is need to pass the test
],
providers: [
DataService, // because this service is using HttpModule
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
答案 0 :(得分:3)
您可以在测试中提供不同的DataService
,如下所示:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ UserComponent ],
imports: [
FormsModule,
],
providers: [
{ provide: DataService, useValue: jasmine.createSpyObj('data', ['someMethod']) }
],
})
.compileComponents();
}));
然后您可以测试组件正确与服务交互的天气。
component.onClick();
expect(component.dataService.someMethod).toHaveBeenCalled();