【问题标题】:Variant of toEqual that works with class properties in the same way that it works with class methodstoEqual 的变体,它使用类属性的方式与使用类方法的方式相同
【发布时间】:2019-04-09 16:10:18
【问题描述】:

这就是场景。第一个类有一个方法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,
  };
}

【问题讨论】:

    标签: jestjs babeljs class-properties


    【解决方案1】:

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

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


    一种选择是创建一个custom matcher,但这很棘手,因为toEqual is doing a lot

    另一种选择是在使用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!
    

    【讨论】:

    • 这里的一个困难是filterFunctions 也会过滤方法。
    • 另外,一个完整的答案需要一个递归步骤来过滤掉嵌套对象中的函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多