How to strictly test objectContaining with jest?

Viewed 23

Is there a way to strictly test .objectConaining with jest?

Basically the code below checks for one of they object keys, and the tests passes, but i don't want it to pass.

Is there some sort of way to test this object strictly, like .toStrictEquals so that the test will not only check for specific keys but for the object structure as well?

it('should work', () => {
  const spy = jest.fn();
  const obj = {
    hello: "world",
    foo: "bar",
  }

  spy(obj);

  expect(spy).toBeCalledWith( expect.objectContaining({
    hello: expect.stringContaining("world")
  }));
});

Basically my goal is to check for obj stricly.

1 Answers

You can do it like this:

it('should work', () => {
  const obj = {
    hello: "world",
    foo: "bar",
  }

  expect(obj).toEqual({
    hello: "world"
  })
});

Which will print the following:

expect(received).toEqual(expected) // deep equality

- Expected  - 0
+ Received  + 1

  Object {
+   "foo": "bar",
    "hello": "world",
  }

   5 |   }
   6 |
>  7 |   expect(obj).toEqual({
     |               ^
   8 |     hello: "world"
   9 |   })
  10 | });
Related