How to expect a Date format by using toMatchObject() in jest

Viewed 42

I am trying to verify wether one of the entry in an object is in ISO timestamp. Using the expect.any($type)

I have tried using Date, ISO_8601, and timestamp. How can I find what is the correct way to define the type here ? Or what should I do to customize one ?

This is a what I am trying to achieve

1 Answers

As per the jest documentation https://jestjs.io/docs/expect#tomatchobjectobject

Use .toMatchObject to check that a JavaScript object matches a subset of the properties of an object. It will match received objects with properties that are not in the expected object.

in your case properties are there, but their values are not the same, so the test will fail.

Here is my solution, its a combination of objectContaining and stringMatching

const actual = {
  time: '2022-08-15T13:43:24.376Z'
};
const isoPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
expect(actual).toEqual(
  expect.objectContaining({ time: expect.stringMatching(isoPattern) })
);

let me know if is not working

Related