我在尝试验证 Angular 5 组件函数中的服务调用时遇到了许多问题。
@Component({
selector: 'app-example',
templateUrl: './app-example.html',
styleUrls: ['./app-example.css'],
providers: [ PersistanceService, AnotherService ]
})
export class ExampleComponent {
callPersist: boolean = false;
private simpleObj = {
"name": "a",
"age" : 20
}
constructor(private persistanceService: PersistanceService, anotherService: AnotherService) {}
persist() {
if (this.callPersist)
this.persistanceService.persist(this.simpleObj);
else
this.anotherService.terminate();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我想验证在调用persist() 时,是否正在调用相应的服务。这是我的测试用例:
it('should call persistService', () => {
let persistService = TestBed.get(PersistanceService); //this is being declared in TestBed.configureTestingModule
spyOn(persistService, 'persist').and.callThrough(); //create spy
component.callPersist = true; //set flag for …Run Code Online (Sandbox Code Playgroud)