我收到错误错误:<toHaveBeenCalled> : Expected a spy, but got undefined.
,我的代码似乎是正确的。
成分:
@Component({
selector: 'no-content',
styleUrls: ['./no-content.component.scss'],
templateUrl: './no-content.component.html',
})
export class NoContentComponent implements OnInit {
public constructor(public errorService: ErrorHandlerService) {
}
public ngOnInit(): void {
this.errorService.showError(null);
}
}
测试:
describe(`no-content`, () => {
let comp: NoContentComponent;
let fixture: ComponentFixture<NoContentComponent>;
let errService: ErrorHandlerService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ NoContentComponent ],
providers: [ErrorHandlerService]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(NoContentComponent);
comp = fixture.componentInstance;
errService = TestBed.get(ErrorHandlerService);
fixture.detectChanges();
});
it('should log ngOnInit', () => {
spyOn(errService, 'showError');
expect(errService.showError(null)).not.toHaveBeenCalled();
comp.ngOnInit();
expect(errService.showError(null)).toHaveBeenCalled();
});
}
我也试过定义存根服务类的变体,但效果是一样的。无论我做什么,我都会得到同样的错误。我无法嘲笑那项服务。 Angular版本4
答案 0 :(得分:1)
expect(errService.showError(null)).toHaveBeenCalled();
已替换为expect(errService.showError).toHaveBeenCalledWith(null);