比较在jest测试用例上包含匿名函数的对象

时间:2019-03-21 18:52:16

标签: javascript react-native jestjs

我在ReactNative项目上使用笑话。我想在一个测试用例中比较两个相同类的对象。这是一个示例类定义:

class Person {
    constructor(id, name, lastName) {
        this.id = id;
        this.name = name;
        this.lastName = lastName;
    }       

    fullName = () => {
        return `${this.name} ${this.lastName}`;
    }
}

我创建了一个测试用例,用于比较Person类的两个对象,它们应该是相同的:

test('checks the Person.constructor method', () => {
    expect(new Person(1, 'John', 'Smith')).toEqual(new Person(1, 'John', 'Smith'));
});

但是我得到以下结果:

 FAIL  __tests__/Comparison-test.js (7.328s)
  ● checks the Person.constructor method

    expect(received).toEqual(expected)

    Expected: {"fullName": [Function anonymous], "id": 1, "lastName": "Smith", "name": "John"}
    Received: {"fullName": [Function anonymous], "id": 1, "lastName": "Smith", "name": "John"}

      48 | 
      49 | test('checks the Person.constructor method', () => {
    > 50 |     expect(new Person(1, 'John', 'Smith')).toEqual(new Person(1, 'John', 'Smith'));
         |                                            ^
      51 | });

      at Object.toEqual (__tests__/Comparison-test.js:50:44)

通过比较期望值和接收值,可以直观地看到它们是相同的,但是由于匿名函数fullName,我知道它们并不相同。

如何比较两个对象?即使两个对象中的匿名函数相同,我也希望能够匿名该函数。

我尝试通过将expect设置为lastName来使用expect.anything()函数。下面的测试实际上通过了:

test('checks the Person.constructor method', () => {
    expect(new Person(1, 'John', 'Smith')).toEqual({
        id: 1,
        name: 'John',
        lastName: 'Smith',
        fullName: expect.anything()});
});

但是,这并不是真正想要的,因为我必须列出要测试的类的所有功能,并且如果我向一个类中添加更多功能,则所有测试都将失败。

那么,有没有一种方法可以在不考虑对象的所有功能的情况下开玩笑地比较同一类的两个对象?

谢谢!

1 个答案:

答案 0 :(得分:4)

您想要的声音toMatchObject与“对象属性的子集”匹配:

test('checks the Person.constructor method', () => {
  expect(new Person(1, 'John', 'Smith')).toMatchObject({
    id: 1,
    name: 'John',
    lastName: 'Smith'
  });  // Success!
});

更新

OP在评论中询问是否还有任何方法可以继续使用实例。

它还可以使用JSON.stringify序列化对象并比较结果:

test('checks the Person.constructor method', () => {
  expect(JSON.stringify(new Person(1, 'John', 'Smith')))
    .toBe(JSON.stringify(new Person(1, 'John', 'Smith')));  // Success!
});