我在测试一个注入到Angular组件中的服务时遇到了麻烦。
这是我面临的一个示例场景。假设有注入了SampleService
的SampleComponent
。我想测试在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();
});
});
无论我是否为spyObject使用and.callThrough()
,我都会得到以下错误:
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
的依赖。
任何形式的意见和建议将不胜感激!
实际上在第二次查看时,代码将服务作为Input
而不是依赖项,因此这就是测试不工作的原因。但是,我还是会把最后的代码贴出来。
import { SampleComponent } from './sample.component';
import { waitForAsync } from "@angular/core/testing";
import { createComponentFactory, Spectator, SpyObject } from "@ngneat/spectator";
describe('SampleComponent', () => {
let spectator: Spectator<SampleComponent>;
let component: SampleComponent;
let sampleService: SpyObject<SampleService>;
const createComponent = createComponentFactory({
component: SampleComponent,
imports: [ CommonModule ],
declarations: [ SampleComponent ],
mocks: [ SampleService ]
});
beforeEach(waitForAsync(() => {
spectator = createComponent();
component = spectator.component;
sampleService = spectator.inject(SampleService);
sampleService.doSomething.and.callThrough();
spectator.detectChanges();
}));
it("should call SampleService.doSomething", () => {
component.handleAction();
expect(spySampleServiceFunction).toHaveBeenCalled();
});
});