大佬教程收集整理的这篇文章主要介绍了Angular:自定义管道的测试用例,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我是单元测试的新手,我需要帮助编写用于 karma 中的 Sort Pipe 的测试用例。我的自定义排序管道正在调用基于 DirectionValue 的方法,其中排序的逻辑是。
@Pipe({
name: 'sortBy'
})
export class SortByPipe implements Pipetransform {
transform(value[],direction:string){
if (direction === 'desc'){
this.descendingSort(value);
}
else if(direction === 'asc'){
this.ascendingSort(value);
}
return value;
}
第一种情况:想检查是否根据方向值调用了正确的方法。
第二种情况:检查排序结果。
我试着为第二种情况写这样的东西。
const direction = 'asc';
const pipe = new SortByPipe();
const result = pipe.transform([4,3,2,1],direction);
expect(result).toBe([1,4]);
请帮助我了解如何解决它。 提前致谢
我认为这个问题有两个答案:
您可以使用 Jasmine Spies (https://jasmine.github.io/api/edge/Spy.html) 在 Jasmine 中进行间谍活动。这允许您有点像点击某个方法并修改它,例如返回模拟值等。它还跟踪调用该方法的次数:
const direction = 'asc';
const pipe = new SortByPipe();
spyOn(pipe,'ascendingSort')
const result = pipe.transform([4,3,2,1],direction);
expect(result).toBe([1,4]);
expect(pipe.ascendingSort).toHaveBeenCalledTimes(1);
升序和降序函数是变换函数实现的一部分(如果没有在其他地方使用),所以函数内部发生了什么并不重要。重要的是输入和预期输出是什么。因此,要测试这样的案例,您只需测试两个用例:
it('should sort in ascending order',() => {
const pipe = new SortByPipe();
const result = pipe.transform([4,'desc');
expect(result).toBe([1,4]);
})
it('should sort in descending order',() => {
const pipe = new SortByPipe();
const result = pipe.transform([1,4],'asc');
expect(result).toBe([4,1]);
})
你真的不在乎测试中会发生什么。如果您决定在转换函数内从两个函数更改为一个函数(如 this.sort(value,direction)
),则您不想修复您的测试。但是,如果您仍然认为应该测试内部功能,那么这是一个很好的指标,您的功能正在做太多事情。因此,在这种情况下,将其分解为更小的函数并为这些函数编写单独的测试以保持测试隔离。
您可以使用 SCURi 编写覆盖率高达 70% 的自动化单元测试
How to write unit test cases automatically using SCURI in angular 8 onWARDs
以上是大佬教程为你收集整理的Angular:自定义管道的测试用例全部内容,希望文章能够帮你解决Angular:自定义管道的测试用例所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。