Best way to match object from a constructor

Viewed 26

We are using Jest testing library. I am quite new to it and I have the following issue. If you want to test an object, where I'd normally use toStrictEqual. But

Object types are checked to be equal. e.g. A class instance with fields a and b will not equal a literal object with fields a and b.

In this case my object comes from a constructor other than Object. So I can not use expect(myObj).toStrictEqual({...}). I'd also not use toMatchObject it doesn't seem a good choice (I need to test that it stores the exact same properties and not a subset.)

I tried to use expect(myObj).toEqual({...}) but it warns me "prefer stricEquality".

This is what I currently run:

test('myTest', () => {
  expect(new OurConstructor(255)).toEqual({
    a: true,
    b: true,
    c: true,
   });
});

What do you think would be the most reasonable approach here? (My current code just ignores that warning.)

1 Answers

One way is to shallow copy the returned object:

  const instance = new myConstructor(255)
  expect({...instance}).toStrictEqual({...})

If it is necessary we can check using toBeInstanceOf

If you can ignore the rule that is also a possibility.

Related