使用业力和茉莉花的.find方法对阵列进行覆盖单元测试 [英] Covering unit test for array with .find method in angular using karma and jasmine

查看:50
本文介绍了使用业力和茉莉花的.find方法对阵列进行覆盖单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用角度8中的karma和jasmine在spec文件中覆盖以下代码的问题

Trouble covering the following piece of code in spec file using karma and jasmine in angular 8

myMethod(id: number): boolean {
  const data= this.myService.getSampleData();
  return data.find(item => item.id === id).count;
}

规格:

it('should call myMethod ', () => {
    spyOn(myService,'getSampleData').and.returnValue(of([{id:1,count:10}]))
    component.myMethod(1);
});

它抛出无法读取未定义的属性.find.虽然我尝试将spyOn(myService,'getSampleData').and.returnValue(of([[{id:1,count:10}])))移入beforeEach函数,但没有运气

It throws cannot read property .find of undefined. Although i tried spyOn(myService,'getSampleData').and.returnValue(of([{id:1,count:10}])) moving into beforeEach function as well but no luck

推荐答案

第一个问题是,当服务似乎返回项目数组时,您正在使用 of 返回Observable.

The first issue is that you are returning an Observable using of when the Service seems to return an array of items.

第二,您没有期望在测试中验证某些东西.

Second, you are not doing any expect to validate something in the test.

我会这样做:

it('should call myMethod ', () => {
    spyOn(myService,'getSampleData').and.returnValue([{id:1, count:10}]);
    expect(component.myMethod(1)).toEqual(true);
});

这篇关于使用业力和茉莉花的.find方法对阵列进行覆盖单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆