简体   繁体   中英

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. 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] .

The test fails because the values for each object property returned from my API endpoint don't match the sample data above. 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?

比较键的数组:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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