【问题标题】:How to write unit test cases for custom sort pipe in angular 4?如何在角度 4 中为自定义排序管道编写单元测试用例?
【发布时间】:2018-11-05 18:30:46
【问题描述】:

import { Pipe, PipeTransform } from "@angular/core";
import { Opportunity } from "../models/Opportunity";

@Pipe({
    name: "orderBy",
    pure: false
})

export class OrderByPipe implements PipeTransform {
    /**
     * Method to sort data and return sorted data
     * 
     * @param records 
     * @param args 
     */
    transform(records: Array<any>, args?: any): any {
        return records.sort(function (a, b) {
            if (a[args.property] < b[args.property]) {
                return -1 * args.order;
            }
            else if (a[args.property] > b[args.property]) {
                return 1 * args.order;
            }
            else {
                return 0;
            }
        });
    }
}

在我的项目中,我必须为多个列实现排序,所以我想在 Angular 4 版本中为上述排序自定义管道编写单元测试用例?

【问题讨论】:

  • 到目前为止你写了哪些单元测试?他们有特定的问题吗?另请注意angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
  • 我有任何记录对象,例如:[{'name':'bharat', 'age':30},{'name':'apple', 'age':32}] 和args = {'property':'name', order: 1 } 并且 pipe 被定义为 OrderPipe 的一个实例,测试用例就像 expect(pipe.transform(data, args)).toEqual(1);并且错误预计 0 等于 1
  • 为什么您希望结果为 1?它怎么可能是0?管道不应该返回排序数组吗?也许从阅读angular.io/guide/testing#pipe-testing开始
  • 在 args 对象中,我已经将 order 定义为 '1',因此控件转到 if case 或 else if case,但控件始终转到 else case。我不明白哪里出错了?

标签: angular unit-testing jasmine karma-jasmine


【解决方案1】:

我在描述中创建了一个管道对象:

const pipe = new OrderByPipe()

然后,进行常见的测试用例,例如:expect(pipe.transform([5,1,6,7]).toEqual([1,5,6,7]),测试极端用例等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多