【发布时间】:2021-12-14 20:51:37
【问题描述】:
我在测试注入 Angular 组件的服务时遇到问题。
这是我面临的一个示例场景。假设我有SampleComponent 注入了SampleService。我想测试在SampleComponent中运行handleAction()是否会调用SampleService.doSomething()。
@Component({
...
})
export class SampleComponent {
constructor(private sampleService: SampleService) { }
handleAction(): void {
this.sampleService.doSomething();
}
}
试用 1
import { SampleComponent } from './sample.component';
import { waitForAsync } from "@angular/core/testing";
import { createComponentFactory, Spectator } from "@ngneat/spectator";
describe('SampleComponent', () => {
let spectator: Spectator<SampleComponent>;
let component: SampleComponent;
const createComponent = createComponentFactory({
component: SampleComponent,
imports: [ CommonModule ],
declarations: [ SampleComponent ],
mocks: [ SampleService ]
});
beforeEach(waitForAsync(() => {
spectator = createComponent();
component = spectator.component;
}));
it("should call SampleService.doSomething", () => {
const sampleService = spectator.inject(SampleService);
const spySampleServiceFunction = spyOn(sampleService, "doSomething").and.callThrough();
component.handleAction();
expect(spySampleServiceFunction).toHaveBeenCalled();
});
});
无论我是否将and.callThrough() 用于 spyObject,我都会收到以下错误。
Error: <spyOn>: doSomething has already been spied upon
试用 2
// same until 'it'
it("should call SampleService.doSomething", () => {
const sampleService = spectator.inject(SampleService);
component.handleAction();
expect(sampleService.doSomething).toHaveBeenCalled();
});
我收到以下错误。
TypeError: Cannot read properties of undefined (reading 'doSomething')
试用 3
如果我将SampleService放入providers,则由于注入到SampleService的依赖关系导致错误。
任何形式的意见和建议将不胜感激!
【问题讨论】:
-
组件中的
SampleService.doSomething();不应为this. sampleService.doSomething(); -
@DrakeAnglin 是的,这是一个错误。刚刚编辑过!
标签: angular unit-testing jasmine angular-test angular-spectator