DEV Community

Chris Cook
Chris Cook

Posted on • Originally published at zirkelc.dev

How To Use expect.objectContaining With Null and Undefined

If you use Jest for testing, you are probably familiar with the expect function and its many matchers. One of the most useful matchers is expect.objectContaining(), which allows you to check whether an object contains a certain set of properties and types.

However, one limitation of expect.objectContaining() is that it does not support null and undefined values. This can be frustrating when testing code that returns properties that are optional or nullable.

I recently came across a workaround for this issue by using the expect.toBeOneOf() matcher from the jest-extended library. This matcher allows you to check whether a value matches one of the expected values, including null and undefined.



test("should not allow null or undefined", async () => {
  const userType = expect.objectContaining({
    id: expect.any(Number),
    name: expect.any(String),
    email: expect.any(String),
  });

  //! email cannot be null or undefined
  expect({
    id: 1,
    name: "John Doe",
    email: undefined,
  }).toEqual(userType);
});

test("should allow null or undefined", async () => {
  const userType = expect.objectContaining({
    id: expect.any(Number),
    name: expect.any(String),
    // allow null and undefined
    email: expect.toBeOneOf([expect.any(String), null, undefined]),
  });

  //> email can be null
  expect({
    id: 1,
    name: "John Doe",
    email: null,
  }).toEqual(userType);

  //> email can be undefined
  expect({
    id: 2,
    name: "Jane Doe",
    email: undefined,
  }).toEqual(userType);
});



Enter fullscreen mode Exit fullscreen mode

In this example, we test whether the given object has a certain set of properties with particular types. For the email property, we use expect.toBeOneOf([expect.any(String), null, undefined]) to allow null, undefined or a string as possible values.

Here is the result of the test run of the two test cases. As expected, the first test case fails because of the undefined value of email. In the second test case, both null and undefined pass the test as valid values.

CodeSandBox

I've prepared a CodeSandBox that lets you try it out quickly without having to go to the trouble of setting up Jest:

Try CodeSandBox


I hope you found this post helpful. If you have any questions or comments, feel free to leave them below. If you'd like to connect with me, you can find me on LinkedIn or GitHub. Thanks for reading!

Top comments (0)