Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[@std/expect] Add optional generics to matchers like toStrictEqual to make it easier to type expected values #6398

Open
AllySummers opened this issue Feb 14, 2025 · 0 comments

Comments

@AllySummers
Copy link

Is your feature request related to a problem? Please describe.

Currently when using matchers like toStrictEqual (and many others), the type of the argument is unknown, which can potentially make it (slightly) slower to make tests correct and ensure type safety. Compared to using assertStrictEquals from @std/assert, it does allow passing a generic.

Allowing us to pass a generic can also help ensure we don't make the same typo if, for example, we have to do a typescript assertion (like if we are using .reduce for an object with inferred keys with Object.entries).

E.g.

import { expect } from 'jsr:@std/expect';

interface Bar = { ... }

interface Foo {
  abc: string;
  def: string;
}

const barToFoo = (bar: Bar): Foo => ({ ... });

Deno.test('given bar, it returns foo', () => {
  const value = barToFoo(bar);

  expect(value).toStrictEqual({
    acb: 'foo', // this would be allowed because the type isn't enforced
    def: 'foo',
  });
});

@std/expect#toStrictEqual source
@std/assert#assertStrictEquals source
@types/jest#toStrictEqual source

Describe the solution you'd like

It would be great if the type of toStrictEqual (and likely other matchers) could accept an optional generic so that we can get IDE completion and type checking for the values we enter, without having to make a separate variable.

E.g.:

Deno.test('given bar, it returns foo', () => {
  const value = barToFoo(bar);

  expect(value).toStrictEqual<Foo>({
    acb: 'foo', // typescript would tell us off here because `acb` isn't a property in `Foo`
    def: 'foo',
  });
});

Describe alternatives you've considered

(Not a big deal) Creating separate variables for the values used in assertions, e.g.:

Deno.test('given bar, it returns foo', () => {
  const value = barToFoo(bar);
  const expected: Foo = {
    acb: 'foo', // typescript would tell us off here because `acb` isn't a property in `Foo`
    def: 'foo',
  };

  expect(value).toStrictEqual(expected);
});

I would be willing to make a PR for this if accepted :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant