我不知道您为什么在这里使用provide 和useClass 来提供这项服务。这通常在您必须自己创建服务的自定义/轻量级实现时完成(例如,当您将 Angular 的 Router 和 ActivatedRoute 作为对控制器的依赖项注入时)。
不过,对于当前场景,您只需要对您创建的服务的注入依赖项的引用。
因此您可以简单地使用providers 数组将其提供给您的测试模块,如下所示:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ModalComponent ],
providers: [ GridService ]
})
.compileComponents();
}));
然后您可以使用fixture.debugElement.injector.get(GridService); 获得对GridService 的引用并像这样测试您的save 方法:
describe('save', () => {
it('should set gridCellUpdated on GridService to false', () => {
let gridService = fixture.debugElement.injector.get(GridService);
expect(gridService.gridCellUpdated).toBeTruthy();
component.save();
expect(gridService.gridCellUpdated).toBeFalsy();
});
});
更新
如果您仍然必须使用provide 提供服务的方式,请使用useClass 而不是use。像这样的:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ModalComponent ],
providers: [ { provide: GridService, useClass: GridServiceMock } ]
})
.compileComponents();
}));
并按照告知的方式编写测试。它应该可以工作。
更新
这是整个测试文件,仅供参考:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { GridService } from './../../services/grid.service';
import { ModalComponent } from './modal.component';
class GridServiceMock {
public gridCellUpdated = false;
}
describe('ModalComponent', () => {
let component: ModalComponent;
let fixture: ComponentFixture<ModalComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ModalComponent ],
providers: [ { provide: GridService, useClass: GridServiceMock } ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
describe('save', () => {
it('should set gridCellUpdated on GridService to false', () => {
let gridService = fixture.debugElement.injector.get(GridService);
expect(gridService.gridCellUpdated).toBeTruthy();
component.save();
expect(gridService.gridCellUpdated).toBeFalsy();
});
});
});
测试通过了:
希望有帮助!