在使用SpyOn文档进行Angular单元测试时出错

问题描述 投票:0回答:1

我正在尝试对组件进行单元测试,我模拟了数据并期望得到一些结果,但得到了一个错误,以下是我的单元测试。

it('should call getData method ', () => {
    const usageService = TestBed.get(UsageService);
    component.slug = 'slugName';
    spyOn(document, 'getElementById').and.returnValue("slugName");
    component.ngOnInit();
    expect(usageService.getData).toHaveBeenCalled();
    });

在上面的单元测试中,我在以下一行得到一个错误 spyOn(document, 'getElementById').and.returnValue("slugName");

错误是:"slugName "类型的参数不能分配给 "HTMLElement "类型的参数。

"slugName "类型的参数不可分配给 "HTMLElement "类型的参数。

这个问题是在升级茉莉花版本后出现的。2.83.5.10

不知道这段代码哪里出了问题,为什么之前还能正常使用,现在升级后就不能使用了。

请帮我解决这个问题。

angular unit-testing jasmine karma-jasmine karma-mocha
1个回答
1
投票

你得到的是一个有效的自述性错误,getElementById的返回类型是:''。HTMLElement 你要回来了 string.

如果你能粘贴你要测试的ngOnInit代码,我们将能更好地帮助你。

不过,你可以从下面的代码中获得帮助。

   it('should call getData method ', () => {
    const usageService = TestBed.get(UsageService);
    spyOn(usageService, 'getData'); // toHaveBeenCalled works on mocked method
    component.slug = 'slugName';
    const htmlEl = document.createElement('div'); // you can create the element which is there in your component.
    spyOn(document, 'getElementById').and.returnValue(htmlEl); // return created element on the previous line.
    component.ngOnInit();
    expect(usageService.getData).toHaveBeenCalled();
   });

0
投票

你想在上面的代码中测试什么?slugName,还是一个服务被调用了?

无论哪种方式,都有更好的方法。

测试slugName是否已经被设置为id。

试着用你的夹具来获取html对象。

即: componentFixture.debugElement.query('#slugName').nativeElement.id

Spy on your service to see if the "getData" component has been subscrib to.

TestBed.inject(UsageService)

我相信get已经被废弃了。

© www.soinside.com 2019 - 2024. All rights reserved.