使用Jest在角度中使用.find方法对数组进行单元测试 [英] Unit test for array with .find method in angular using jest
问题描述
如何使用.find方法以角度获取数组的覆盖率.我在下面的代码段遇到了麻烦.
How to get coverage for array with .find method in angular. I'm getting trouble in the below piece of code.
sample.component.ts
sample.component.ts
public permissions = [{id: 0, value: 'fruit' }, {id: 1, value: 'vegetable'}];
this.filteredList = this.permissions.slice();
public isFiltered(permission) {
return this.filteredList.find(item => item.id === permission.id);
}
sample.spec.ts
sample.spec.ts
it('should call myMethod ', () => {
expect(component.isFiltered(1)).toEqual(true);
});
我遇到以下错误,
TypeError: Cannot read property 'find' of undefined
任何帮助将不胜感激
推荐答案
像这样写
it('should call myMethod ', () => {
let permissions = [{id: 0, value: 'fruit' },{id: 1, value: 'vegetable'} ];
component.filteredList = permissions.slice();
expect(component.isFiltered({id:1}).value).toEqual('vegetable');
});
您需要为component.filteredList
更新
在ts中使用persmissions.id
进行过滤时,需要将具有属性id
的对象(进行过滤)传递给isFiltered()
.同样,isFiltered
不会返回布尔值,而是对象(即搜索结果本身),因此我们将其值检查为必需的
as you are using persmissions.id
in your ts to filter you need to pass an object with property id
(to filter by) to isFiltered()
. Also isFiltered
does not returns a boolean but the object (i.e. search result itself) so we check its value to be the required one
这篇关于使用Jest在角度中使用.find方法对数组进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!