Shiyu Wang
Shiyu Wang

Reputation: 61

Jest: How to test for optional object keys

Say, I have an object below

const obj1 = {name: expect.any(String)}

Backend return response as below with object the key 'age' as optional key

const response = {name: 'bbb', age: 10}

So, how can I assert obj1 have age as the optional key, which means if it exists, it must be number type, if it doesn't exist, we can omit the checking ?

expect(response).toMatchObject(obj1);

Upvotes: 6

Views: 3830

Answers (2)

ehrencrona
ehrencrona

Reputation: 6982

I don't think there's a built-in function for that, but toMatchObject along with destructuring can do what you need:

expect({
  age: 0, 
  ...response
}).toMatchObject(obj1);

If age is not present in the object, it will assume 0; if it is present, it will use the present value and therefore fail if it's the wrong type.

Upvotes: 5

Hussain Ali Akbar
Hussain Ali Akbar

Reputation: 1655

From what i can understand, you want to check that if the property is defined, check that its type is a number? And if the property does not exist then do not check the property type? Correct?

Assuming that the above understanding is correct, this should do:

        const response = {name: "bbb", age:10};
        if (response.age) {
            if (typeof response.age === 'number') {
            console.log("age is a number");
            //your logic if age is a number
            }
            else {
            //your logic in case age exists but its not a number
            }
        }
        else {
        //your logic in case age does not exist
        }

Upvotes: -4

Related Questions