0

我在测试注入 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

任何形式的意见和建议将不胜感激!

4

1 回答 1

0

实际上,第二次看,代码将服务作为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();
    });
});
于 2021-11-02T21:31:00.013 回答