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

Added expect.satisfies(predicate) matcher #14145

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

johnw42
Copy link

@johnw42 johnw42 commented May 16, 2023

Summary

This PR adds a new matcher, expect.satisfies(predicate), similar to toSatisfy matcher from the jest-extended package but implemented as an asymmetric matcher for more flexibility. It is useful for composing with other expectation functions to test for arbitrary conditions without going outside the expect(subject).toVerb(object) pattern.

For example, consider the example code for expect.objectContaining(object), but modified to accept only even numbers:

test('onPress gets called with the right thing', () => {
  const onPress = jest.fn();
  simulatePresses(onPress);
  const isEven = (n) => n % 2 === 0;
  expect(onPress).toHaveBeenCalledWith(
    expect.objectContaining({
      x: expect.satisfies(isEven), // Prints as "Satisfies isEven"
      y: expect.satisfies(isEven),
    }),
  );
});

Without expect.satisfies, the expect call has to be totally rewritten in a way that's harder to read and produces much less helpful error messages:

let isOk = false;
for (const [arg] of onPress.mock.calls) {
  if (isEven(arg.x) && isEven(arg.y)) {
    isOk = true;
    break;
  }
}
expect(isOk).toBe(true);

For further motivation, consider the Truly matcher from Gtest, which is used in numerous places in Chromium.

Test plan

This PR includes full unit tests for the new functionality.

@linux-foundation-easycla
Copy link

linux-foundation-easycla bot commented May 16, 2023

CLA Signed

The committers listed above are authorized under a signed CLA.

@netlify
Copy link

netlify bot commented May 16, 2023

Deploy Preview for jestjs ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit e194155
🔍 Latest deploy log https://app.netlify.com/sites/jestjs/deploys/6463c546f5846e000841ed60
😎 Deploy Preview https://deploy-preview-14145--jestjs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site settings.

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

Successfully merging this pull request may close these issues.

None yet

1 participant