我在测试注入 Angular 组件的服务时遇到问题。
这是我面临的一个示例场景。假设我SampleComponent
已经SampleService
注射了。我想测试是否handleAction()
在SampleComponent
调用中运行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
。
任何形式的意见和建议将不胜感激!