1

这就是场景。第一个类有一个方法getName,第二个类有一个类属性getName。第一类适用于toEqual,而第二类则不适用。

class Person01 {
    constructor(name) { this.name = name; }
    getName() { return this.name; }
}

class Person02 {
    constructor(name) { this.name = name; }
    getName = () => { return this.name; }
}

const testCases = [
    [
        // passes
        new Person01('Alan', 'Kay'),
        new Person01('Alan', 'Kay'),
    ], 
    [
        // fails due to class properties
        new Person02('Alan', 'Kay'),
        new Person02('Alan', 'Kay'),
    ]
];

describe('when one class has the same values that another class has', () =>
    testCases.forEach(pair =>
        it('is considered to be equal to that class', () =>
            expect(pair[0]).toEqual(pair[1]))));

这是第二类的失败消息。

Expected: {"firstName": "Alan", "getName": [Function anonymous], "lastName": "Kay"} 
Received: {"firstName": "Alan", "getName": [Function anonymous], "lastName": "Kay"} 

我们当前的解决方法是JSON.parse(JSON.stringify(obj))在实际值和预期值上运行。

相反,我们正在寻找的是一种变体,toEqual它对类属性的工作方式与对类方法的工作方式相同。

这是我们的 babel.config.js 文件。

module.exports = function (api) {

  api.env();

  const plugins = [
    "@babel/proposal-class-properties",
  ];

  return {
    plugins,
  };
}
4

1 回答 1

1

问题是每个实例都创建了函数类属性......

...所以toEqual失败了,因为每个实例都有一组不同的函数属性。


一种选择是创建一个自定义匹配器,但这很棘手,因为toEqual 它做了很多事情

另一种选择是在使用之前过滤函数属性toEqual

const filterFunctions = (obj) => 
  Object.keys(obj)
    .filter(k => typeof obj[k] !== 'function')
    .reduce((a, k) => { a[k] = obj[k]; return a; }, {});

describe('when one class has the same values that another class has', () =>
  testCases.forEach(pair =>
      it('is considered to be equal to that class', () =>
          expect(filterFunctions(pair[0])).toEqual(filterFunctions(pair[1])))));  // Success!
于 2019-04-09T02:56:49.580 回答