How can you match on wildcard object keys using Jest matchers?

197 Views Asked by At

Presume that you have this value, where you can't predict the value of the keys in foo:

{
  context: { version: 1.0 },
  value: {
    foo: {
      afh34q2: [1n, 100n],
    }
  }
}

How can I write a strict matcher that treats the keys as wildcards and asserts on the values only?

expect(value).toStrictEqual({
  context: expect.objectContaining({
    version: expect.any(String),
  }),
  value: {
    foo: /* how to match on only the object values? */
  }
});
1

There are 1 best solutions below

0
Esteban Térrez On

I don't think there's a way to describe in a single assertion the object containing dynamic keys, probably because if you define the assertion like this

// ... 
foo: expect.objectContaining({ [expect.any(String)]: [1n, 100n] })

there wouldn't be a way do define the matcher object with multiple keys, amount of expected keys or the different possible values.

So what I would do is write a separate assertion on the value.foo property like this

    test('should have string keys and number array values', () => {
        expect(Object.entries(value.value.foo)).toEqual([
            [expect.any(String), [1, 100]]
        ]);
    });

repl.it example