我在测试注入到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的依赖项而导致错误。
任何类型的建议和建议都将不胜感激!
发布于 2021-11-02 21:31:00
实际上,在第二次查看时,代码将服务作为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();
});
});https://stackoverflow.com/questions/69774645
复制相似问题