pmiranda
pmiranda

Reputation: 8420

Jest, match to regex

Currently I have this test:

import toHoursMinutes from '../../../app/utils/toHoursMinutes';

describe('app.utils.toHoursMinutes', () => {
  it('should remove 3rd group of a time string from date object', async () => {
    expect(toHoursMinutes(new Date('2020-07-11T23:59:58.000Z'))).toBe('19:59');
  });
});

What toHoursMinutes does is to receive a Date object and transform it like this way:

export default (date) => `${('' + date.getHours()).padStart(2, '0')}:${('' + date.getMinutes()).padStart(2, '0')}`;

My local time offset is -4 so my test pass ok if I compare 23:59 with 19:59, but I want to run the test anywhere, so I prefer to compare the output of toHoursMinutes() with a regex expression like this one, that check the hh:mm format: ^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$

But how can I use a regex to compare instead a explicit string?

I tried this:

const expected = [
  expect.stringMatching(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/)
];
it.only('matches even if received contains additional elements', () => {
  expect(['55:56']).toEqual(
    expect.arrayContaining(expected)
  );
});

But I get a:

Expected: ArrayContaining [StringMatching /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/]
Received: ["55:56"]

Upvotes: 19

Views: 31132

Answers (3)

Devi
Devi

Reputation: 1

In my case, I can check the format of a time in a span using toHaveTextContent().

const span = screen.getByRole("presentation", { name: /time/i });
expect(span).toHaveTextContent(/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/);

Docs for toHaveTextContent(): https://github.com/testing-library/jest-dom#tohavetextcontent

Upvotes: 0

swift-lynx
swift-lynx

Reputation: 3765

There is a toMatch function on expect() that does just that.

expect('12:59').toMatch(/^\d{1,2}:\d{2}$/); // stripped-down regex

https://jestjs.io/docs/expect#tomatchregexp--string

If you want to match a regex inside of other jest functions, you can do so by using expect.stringMatching(/regex/).

expect({
  name: 'Peter Parker',
}).toHaveProperty('name', expect.stringMatching(/peter/i))

https://jestjs.io/docs/expect#expectstringmatchingstring--regexp

Upvotes: 36

pmiranda
pmiranda

Reputation: 8420

I was ok except in the dummy data because wasn't for the regex. In case anyone need it, this works:

const expected2 = [
  expect.stringMatching(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/)
];
it('matches even if received contains additional elements', () => {
  expect(['12:59']).toEqual(
    expect.arrayContaining(expected2)
  );
});

Upvotes: 3

Related Questions