Angular:定制管道的测试用例
我是单元测试新手,我需要帮助为karma中的Sort Pipe编写测试用例。我的自定义排序管道正在调用基于DirectionValue的方法,其中排序逻辑为Angular:定制管道的测试用例,angular,karma-jasmine,angular-unit-test,Angular,Karma Jasmine,Angular Unit Test,我是单元测试新手,我需要帮助为karma中的Sort Pipe编写测试用例。我的自定义排序管道正在调用基于DirectionValue的方法,其中排序逻辑为 @Pipe({ name: 'sortBy' }) export class SortByPipe implements PipeTransform { transform(value[], direction:string){ if (direction === 'desc'){ this.descendingS
@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,2,3,4]);
请帮助我了解如何解决它。
提前谢谢我想这个问题有两个答案:
const direction = 'asc';
const pipe = new SortByPipe();
spyOn(pipe, 'ascendingSort')
const result = pipe.transform([4,3,2,1], direction);
expect(result).toBe([1,2,3,4]);
expect(pipe.ascendingSort).toHaveBeenCalledTimes(1);
it('should sort in ascending order', () => {
const pipe = new SortByPipe();
const result = pipe.transform([4,3,2,1], 'desc');
expect(result).toBe([1,2,3,4]);
})
it('should sort in descending order', () => {
const pipe = new SortByPipe();
const result = pipe.transform([1,2,3,4], 'asc');
expect(result).toBe([4,3,2,1]);
})
你真的不在乎测试中发生了什么。如果您决定在transform函数中从两个函数更改为一个函数(如
this.sort(value,direction)
),则不希望修复测试。但是,如果您仍然认为内部功能应该进行测试,这是一个很好的指标,表明您的功能做了太多的事情。因此,在这种情况下,将其拆分为更小的函数,并为这些函数编写单独的测试,以保持测试的隔离。您可以使用SCURi编写覆盖率高达70%的自动化单元测试
错误是什么?最初是这个
预期[4,3,2,1]为[1,2,3,4]。提示:要检查深度相等,请使用.toEqual()而不是.toBe()。
然后我将toBe改为toEqual,然后它会给出以下明显的错误<代码>错误:预期$[0]=4等于1。预期$[1]=3等于2。预期$[2]=2等于3。预计$[3]=1等于4我尝试了SpyMethod和您建议的第二个解决方案,但它也给出了与我在上述注释中描述的相同的错误<代码>错误:预期[4,3,2,1]为[1,2,3,4]。提示:要检查深度相等,请使用.toEqual()而不是.toBe()。噢,只需使用toEqual()。它们做的有点相同,但toBe检查对象引用是否相同,是否与toEqual一样处理字符串、数字和布尔等基本类型。对于数组和对象,您可以使用toEqual仅比较内容,但如果内容完全相同,则不进行比较。我无法这样做,因为它的不相等数组toEqual()将给出以下错误`错误:预期$[0]=4等于1。预期$[1]=3等于2。预期$[2]=2等于3。预期$[3]=1等于4``这似乎测试失败了,对吗?现在仔细检查一下,我想我在测试中把'desc'和'asc'混在一起了,所以这很可能就是为什么你会出错的原因。