【问题标题】:Error while performing angular Unit testing with SpyOn document使用 SpyOn 文档执行角度单元测试时出错
【发布时间】:2020-09-09 06:40:07
【问题描述】:

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

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”类型的参数不能分配给类型参数 'HTML元素'。

jasmine 版本从 2.8 升级到 3.5.10

后出现此问题

我不知道这段代码有什么问题,为什么以前可以正常工作,现在升级后就不行了。

请帮我解决问题。

【问题讨论】:

  • getElementById 应该返回一个 HTML 元素。但是你的模拟返回一个字符串。这没有意义,这就是你有错误的原因。

标签: angular unit-testing jasmine karma-jasmine karma-mocha


【解决方案1】:

您想在上面的代码中测试什么? slugName,或者服务已被调用?

不管怎样,有更好的方法来做到这一点。

测试 slugName 是否已设置为 id

尝试使用您的夹具来获取 html 对象:

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

监视您的服务以查看“getData”组件是否已被订阅。

TestBed.inject(UsageService)

我相信 get 已被弃用。

【讨论】:

    【解决方案2】:

    您收到一个有效且自我描述的错误,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();
       });
    

    【讨论】:

      猜你喜欢
      • 2018-11-16
      • 2021-05-07
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2020-03-06
      • 1970-01-01
      相关资源
      最近更新 更多