如何在 javascript 中测试两个具有不同参数值的返回函数?

How to test two returned functions with different argument value in javascript?

我有一个函数 returns comparisonFunction

  getComparisonFunction(propertyOfComparison) {
    const func = function(a, b){
      if ( a[propertyOfComparison] < b[propertyOfComparison] ) {
        return -1;
      }
      if ( a[propertyOfComparison] > b[propertyOfComparison] ) {
        return 1;
      }
      return 0;
    };

    return func;
  }

此方法将在javascript "sort" 方法中使用。 例如:

arrayOfObjects.sort(getComparisonFunction('name'));

此方法将 "arrayOfObjects" 按 "name" 属性 排序。 方法工作正常,问题是: 我如何比较具有不同参数的函数调用

  it('should get correct comparison function', function () {
    const func = component.getComparisonFunction('testProperty');

    const expectedFunc = function(a, b){
      if ( a['testProperty'] < b['testProperty'] ) {
        return -1;
      }
      if ( a['testProperty'] > b['testProperty'] ) {
        return 1;
      }
      return 0;
    };

    expect(func.toString()).toEqual(expectedFunc.toString());
  });

这就是我现在拥有的,但它不起作用。 运行 代码后我收到的错误是:

 Expected 'function (a, b) {
                if (a[propertyOfComparison] < b[propertyOfComparison]) {
                    return -1;
                }
                if (a[propertyOfComparison] > b[propertyOfComparison]) {
                    return 1;
                }
                return 0;
            }' to equal 'function (a, b) {
                if (a['testProperty'] < b['testProperty']) {
                    return -1;
                }
                if (a['testProperty'] > b['testProperty']) {
                    return 1;
                }
                return 0;
            }'.

检查函数的代码作为测试非常非常脆弱并且很容易破坏给你一个假阴性:

let someFn = function(a, b) {
  return a + b;
}

let expected = `function(a, b) {
  return a + b;
}`

console.log("Test original implementation:", test(someFn.toString(), expected));

//later the code style is changed to remove extra whitespace and make it one line
someFn = function(a, b) { return a+b; }

console.log("Test updated implementation:", test(someFn.toString(), expected));

//simple testing
function test(expected, actual) {
  return expected == actual
}

仅对代码进行 non-functional 更改就会破坏测试。

更糟糕的是,如果代码有 功能更改,测试无法保证新实现的行为与旧实现一样,因为它只查看代码的结构代码:

//simplified case of what the actual code could be doing
function someCodeBaseFunction() {
  let someInput = [8, 12, 42];
  return someFn(...someInput)
}

let someFn = function(a, b) { return a+b; }

let expected = `function(a, b) { return a+b; }`

console.log("Test original implementation:", test(someFn.toString(), expected));

console.log("Codebase usage:", someCodeBaseFunction()); //20, as the third number is ignored

//new implementation
someFn = function(...args) { 
  return args.reduce((a, b) => a + b); 
}

//update the test, so it passes
expected = `function(...args) { 
  return args.reduce((a, b) => a + b); 
}`

console.log("Test updated implementation:", test(someFn.toString(), expected));

//some existing line of code
console.log("Codebase usage:", someCodeBaseFunction()); //62, as the third number is now used

//simple testing
function test(expected, actual) {
  return expected == actual
};

相反,您想要做的是测试代码的 行为 并在那里设置您的期望。这样,如果实现发生变化,您可以确保实现仍然符合同一组期望。

在这种情况下,您需要创建一个最初无序的示例输入,尝试对其进行排序,然后期望该顺序按您预期的方式工作。在 pseudo-code 中看起来有点像这样:

//arrange
input = [
 {testProperty: "c", id: 1},
 {testProperty: "a", id: 2},
 {testProperty: "d", id: 3},
 {testProperty: "b", id: 4}
];

expected = [
 {testProperty: "a", id: 2},
 {testProperty: "b", id: 4},
 {testProperty: "c", id: 1},
 {testProperty: "d", id: 3}
];

//act
input.sort(component.getComparisonFunction('testProperty'))

//assert
expect(input).toEqual(expected);

如果需要,您还可以在更精细的级别添加更多测试,以进一步约束期望。比如你要保证比较的是case-sensitive

//arrange
a = { testProperty: "a" };
b = { testProperty: "B" };

//act
result = component.getComparisonFunction('testProperty')(a, b)

//assert
expect(result).toBeGreaterThanOrEqual(1)

或case-insensitive:

//arrange
a = { testProperty: "a" };
b = { testProperty: "B" };

//act
result = component.getComparisonFunction('testProperty')(a, b)

//assert
expect(result).toBeLessThanOrEqual(-1)

这更清楚地定义了您的期望,并确保未来的更改将完全满足您的需求。

如果您想通过提供的任何参数实现排序,您可以尝试以下操作:

const array=[
  {name:'C',Key:'14',val:3},
  {name:'B',Key:'12',val:2},
  {name:'A',Key:'11',val:1},
  {name:'D',Key:'16',val:4},
  {name:'E',Key:'18',val:5}
];

console.log(array);

function comparer(prop){
  return function(a,b){
    return a[prop]-b[prop];
  }
};
array.sort(comparer('Key'));
console.log(array);
array.sort(comparer('val'));
console.log(array);

此外,要对其进行测试,只需像上面那样使用测试用例,并检查其排序是否符合您的实现。