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