简体   繁体   English

期望对象拥有所有给定的属性

[英]Expect object to have all given properties

I'm writing unit tests for my Node.js application using Jest and I'm trying to test whether or not an API endpoint returns an object with a set of pre-determined properties. 我正在使用Jest为我的Node.js应用程序编写单元测试,并且我正在尝试测试API端点是否返回具有一组预定属性的对象。 I have the following: 我有以下内容:

const sampleResponse = {
  "Game": "GameName",
  "World": "2",
  "Location": "ServerLocation",
  "Timestamp": 1516204557853,
  "alive": true,
  "time": 10.1,
  "min": 8.927,
  "max": 10.154,
  "avg": 9.409
};

I then used the following code to test for object properties: 然后我使用以下代码来测试对象属性:

test("Location for server cluster exists, and returns an array of objects", () => {
  return Request(Routes.LocationSpecific).then((result) => {
    expect(result[0]).toMatchObject(sampleResponse);
  });
});

Where result is an array of objects containing data similar to the above object, and I'm simply matching result[0] . 其中result是包含与上述对象类似的数据的对象数组,我只是匹配result[0]

The test fails because the values for each object property returned from my API endpoint don't match the sample data above. 测试失败,因为从我的API端点返回的每个对象属性的值与上面的示例数据不匹配。 The properties exist, the red appears in my terminal from the values not matching, but I'd like to get it green. 属性存在,红色出现在我的终端中,不匹配的值,但我想让它变绿。

Is there a way to match all given properties of result[0] to a sample object, regardless of their values? 有没有办法将result[0]所有给定属性与样本对象相匹配,无论它们的值如何?

比较键的数组:

expect(Object.keys(result[0])).toEqual(Object.keys(sampleResponse));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM