首页 > 解决方案 > 具有服务参数的组件的角度单元测试

问题描述

我是角度和单元测试的新手,我正在尝试为带有服务的组件编写一个单元测试,其中服务 url 是从@Input()值中获取的。

cms-sonor.component.ts

export class CmsSonarComponent implements OnInit {
    @Input() configParam;
    sonarData;
    constructor(public cmsService: CmsService) {}

    ngOnInit(): void {
        this.cmsService
            .getData(this.configParam.url, { responseType: "text" })
            .subscribe(
                (resp) => {
                    this.sonarData = resp;
                },
                (err) => {
                    console.log(err);
                }
            );
    }
}

cms-sonar.component.spec.ts

describe("CmsSonarComponent", () => {
    let component: CmsSonarComponent;
    let injector: TestBed;
    let fixture: ComponentFixture<CmsSonarComponent>;
    let service: CmsService;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            declarations: [CmsSonarComponent, SonorPipe],
            providers: [
                {
                    provide: CmsService,
                    useValue: {
                        getData: () => of({ id: 123, name: "Product" }),
                    },
                },
            ],
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(CmsSonarComponent);
        service = TestBed.get(CmsService);
        component = fixture.componentInstance;
        //fixture.detectChanges();
    });

    it("should create", () => {
        expect(component).toBeDefined();
    });

    it("testing cms sonar ngOnInit", () => {
        spyOn(service, "getData").and.callThrough();
        component.ngOnInit();
        fixture.detectChanges();
        expect(service.getData).toHaveBeenCalledWith("/getData", "json");
        expect(component.sonarData).toEqual({ id: 123, name: "Product" });
    });
});

错误 TypeError: Cannot read property 'url' of undefined

你能告诉我我犯了什么错误吗?任何帮助表示赞赏。

我什至尝试使用这样的 argsspyOn(service, 'getData') .withArgs('abc')

Update-1 我能够解决上述问题,URL 试图获取输入值。

const configParam = {
    url: 'visible'
};
beforeEach(() => {
        fixture = TestBed.createComponent(CmsSonarComponent);
        service = TestBed.get(CmsService);
        component = fixture.componentInstance;
        component.configParam = configParam;
        //fixture.detectChanges();
    });
it('testing cms sonar ngOnInit', () => {
        spyOn(service, 'getData').and.callThrough();
        component.ngOnInit();
        fixture.detectChanges();
        expect(service.getData).toHaveBeenCalledWith('visible', {
            responseType: 'text'
        });
        expect(component.sonarData).toEqual({ id: 123, name: 'Product' });
    });

但现在我得到了这个错误

Expected spy getData to have been called with:
  [ 'visible', Object({ responseType: 'text' }) ]
but actual calls were:
  [ 'visible' ],
  [ 'visible' ]

对此的任何指南都将受到高度赞赏。

标签: angularunit-testingjasminekarma-jasmine

解决方案


推荐阅读