Jest 将对象与任意 属性 值进行比较

Jest compare object with arbitrary property value

我正在用 Jest 测试 rest API。我知道我们使用 toEqual 通过递归比较所有属性来检查两个对象是否相等。

对于原始值 toEqual 使用 Object.is 进行比较。

问题

我遇到的问题是在测试 /register 端点时。用户成功注册后,端点 returns 用户详细信息。使用详细信息包含 phone、姓名、电子邮件等信息,在这种情况下更重要的是 user_id.

现在,我正在尝试的是这样的:

const data = {
  sponsor_id: 'ROOT_SPONSOR_ID',
  phone: '9999999999',
  name: 'Joe',
  password: 'shhhhh'
};

// Some API call goes here which returns `body`

expect(body).toEqual({
  user_id, // <-- How to test value of this?
  sponsor_id: data.sponsor_id,
  phone: data.phone,
  name: data.name
});

我事先不知道 user_id 字段的返回值是什么。我只知道这将是一个数字。现在它可以是任何数值那么在这种情况下如何用任何值或任何数值测试一个对象属性?

有一件事我还想检查我发送的数据(属性)是否超出了我的预期。 顺便说一句,使用 toEqual已经在处理了。

如果我的测试方法有缺陷,请提供更好的方法并进行一些解释。

使用expect.any(Number)确保user_idNumber:

test('matches', () => {

  const data = {
    sponsor_id: 'ROOT_SPONSOR_ID',
    phone: '9999999999',
    name: 'Joe',
    password: 'shhhhh'
  };

  const user_id = Math.floor(Math.random() * 1000);
  const body = Object.assign(data, { user_id });

  expect(body).toEqual({
    user_id: expect.any(Number),  // user_id must be a Number
    sponsor_id: data.sponsor_id,
    phone: data.phone,
    name: data.name,
    password: data.password
  });  // SUCCESS

});

请注意,如果您想要更具体的匹配器,您可以 create your own 使用 expect.extends