Manu Chadha
Manu Chadha

Reputation: 16729

How to test that a JavaScript object has only specific fields/properties

I have this function which tests that an object has certain fields

validateServerResponseStructure(res: any) {
    let isTypeCorrect: boolean = (
      res.result != undefined) && (res['additional-info'] != undefined
    );
    return isTypeCorrect;
  }

Is there a way to test that res has only result and additional-info properties and nothing else?

Upvotes: 0

Views: 929

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370639

Just check that the length of its keys is exactly two. Also, probably best to use strict equality comparison, if you want to ensure that the properties are not undefined:

validateServerResponseStructure(res: any) {
  let isTypeCorrect: boolean = (
    res.result !== undefined
    && res['additional-info'] !== undefined
    && Object.keys(res).length === 2
  );
  return isTypeCorrect;
}

In the unusual case that you may have properties that contain the undefined value, and you want to permit such values, check the length of the keys, and that both result and additional-info are included in the keys:

const keys = Object.keys(res);
let isTypeCorrect: boolean = (
  ['result', 'additional-info'].every(key => keys.includes(key))
  && keys.length === 2
)

Upvotes: 2

Related Questions