ava icon indicating copy to clipboard operation
ava copied to clipboard

Allow regexes in `t.like`

Open tommy-mitchell opened this issue 11 months ago • 4 comments

The message property in t.throws is really ergonomic - it can be a string, RegExp, or even a function. t.like should be just as ergonomic with strings:

const output = foo();

t.like(output, {
  name: 'foo',
  source: /foo comes from/,
});

A motivating example is trying to convert this test from npm-user to use t.like:

const user = await npmUser('sindresorhus');

t.like(user, {
	name: 'Sindre Sorhus',
	avatar: /npm-avatar/,
	email: '[email protected]',
});

tommy-mitchell avatar Feb 26 '24 05:02 tommy-mitchell

Currently like is a partial deepEqual, selecting from the actual (first argument) just those properties that exist in the expected (second argument). How would we do that if expected contains a regular expression value?

novemberborn avatar Feb 27 '24 20:02 novemberborn

Currently like is a partial deepEqual, selecting from the actual (first argument) just those properties that exist in the expected (second argument). How would we do that if expected contains a regular expression value?

Saberian1992 avatar Mar 30 '24 23:03 Saberian1992

Maybe:

  • If expected.prop is a RegExp and actual.prop is a string:

    1. Check if actual.prop matches expected.prop

    2. If false, fail the test. The current descriptors (string vs regex) can stay as-is:

    - str: 'string',
    + str: /string/,
    
  • If expected.prop is a RegExp and actual.prop is a RegExp:

    1. No change. Only pass if the two regexes are the same.
  • If expected.prop is a string and actual.prop is a RegExp:

    1. No change. The test should still fail.

tommy-mitchell avatar Jul 22 '24 02:07 tommy-mitchell

I agree that this looks useful, and your logic makes sense, but I don't immediately see how this could be implemented. Don't let that stop you though 😉

It may also technically be a breaking change, in that if you've written an existing assertion expecting a regular expression, and your actual value changes to a string, that happens to match… the test passes when it shouldn't. OK that seems unlikely.

novemberborn avatar Aug 02 '24 13:08 novemberborn