【发布时间】:2020-08-16 08:27:48
【问题描述】:
我希望使用 Angular 的(第 7 版)TestBed 来测试一个组件,并查看注入的服务是否有调用的方法。
看着这个this tutorial,大约23:18他展示了如何创建茉莉花天空,因此您可以使用toHaveBeenCalledTimes等测试方法
我正在尝试做同样的事情,除了使用TestBed 创建组件而不是像视频中那样手动实例化。
我有以下..
describe('AppComponent', () => {
beforeEach(async(() => {
fakeStartupService = jasmine.createSpyObj(fakeStartupService, ['start']);
//fakeStartupService.start.and.returnValue(null);
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
],
providers: [
ErrorHandler,
{ provide: StartupService, useValue: fakeStartupService },
],
declarations: [
AppComponent,
],
}).compileComponents();
}));
it('should have called start services start'), () => {
expect(fakeStartupService.start).toHaveBeenCalledTimes(100);
}
});
第一个问题是,当我输入 expect(fakeStartupService. 时,我没有像视频中那样显示 start 方法的代码完成。
另一个(主要)问题是,虽然上面的编译和运行,我认为我不正确,因为 expect(fakeStartupService.start).toHaveBeenCalledTimes(100); 确实 not 失败 - 组件只调用它一次,但我断言 100 次,所以它应该失败。
我猜测在{ provide: StartupService, useValue: fakeStartupService }, 中使用useValue,所以这可能是不正确的
我想知道:是否可以使用这样的间谍,如果可以,我该怎么做?
更新
实际上我有一个语法错误(描述后的括号)。
以下似乎对我有用。
it('should have called start services start once', async () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
// As ngOnInit is async, use detectChanges and whenStable to wait for it to be finished.
fixture.detectChanges();
await fixture.whenStable()
expect(fakeStartupService.start).toHaveBeenCalledTimes(1);
});
另外,等我异步ngOnInit我添加了
fixture.detectChanges();
await fixture.whenStable()
现在,唯一的小问题是他们如何在视频中获得 Intellisense。
【问题讨论】:
标签: angular jasmine karma-jasmine angular-test