在了解了Java语言comparison operators === and ==之间的区别之后,我感到非常惊讶,茉莉花平等概念不符合任何一个。例如,以下测试套件中的所有语句都是正确的:

describe('Jasmine asserted equality of objects', function() {

    it('is different from ===- and ==-equality', function() {
        var x = {};
        var y = {};

        expect(x === y).toBeFalsy();
        expect(x == y).toBeFalsy();
        expect(x).toEqual(y);
    });

    it('seems to imply element-wise equality', function() {
        var x = {'name': 'value'};
        var y1 = {'name': 'values'};
        var y2 = {'names': 'value'};
        var y3 = {'name': 'value'};

        expect(x).not.toEqual(y1);
        expect(x).not.toEqual(y2);
        expect(x).toEqual(y3);
    });

    it('does not imply equality of the respective prototypes', function() {
        var x = {};
        var y = Object.create(x);
        var pr = Object.getPrototypeOf;

        expect(x).toEqual(y);
        expect(pr(pr(x))).not.toEqual(pr(pr(y)));
    });

});


不幸的是,我找不到Jasmine的任何官方API文档。众所周知的introduction page仅提供示例,我发现的大多数其他资源都讨论了===和==的区别或Jasmines概念的custom matchers

但是,我的主要问题是:如何指定Jasmines函数toEqual?另外,我会对引入这种新的平等概念的原因感兴趣:为什么expect(x).toEqual(y)或在哪种情况下比x === y(或x == y)更合适?

最佳答案

DSL茉莉花具有平等的概念,因为javascript中的平等可以是confusing,而在测试中的readabilty是重要的。似乎在设计茉莉花时,他们决定采用underscore.js平等的概念。

要回答如何指定茉莉花toEqual,您可以在github的source中看到。

getJasmineRequireObj().toEqual = function() {

  function toEqual(util, customEqualityTesters) {
    customEqualityTesters = customEqualityTesters || [];

    return {
      compare: function(actual, expected) {
        var result = {
          pass: false
        };

        result.pass = util.equals(actual, expected, customEqualityTesters);

        return result;
      }
    };
  }

  return toEqual;
};


正如我们在上面看到的,使用util.equals()反过来又来自内部使用eq函数的matchersUtil函数。

    getJasmineRequireObj().matchersUtil = function(j$) {
      // TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter?

      return {
        equals: function(a, b, customTesters) {
          customTesters = customTesters || [];

          return eq(a, b, [], [], customTesters);
        },
    ...
      // Equality function lovingly adapted from isEqual in
      //   [Underscore](http://underscorejs.org)
      function eq(a, b, aStack, bStack, customTesters) {
        var result = true;
      ...
     }
 };

07-28 09:06