Skip to content

this.equals not available in custom matcher #8295

Closed
@christophgysin

Description

@christophgysin

🐛 Bug Report

Depending on how a custom matcher is used, this.equals might not be defined:

To Reproduce

Steps to reproduce the behavior:

expect.extend({
  customMatcher(/* received, expected */) {
    const response = {
      pass: this.equals !== undefined,
      message: `this.equals is ${this.equals ? 'defined' : 'undefined'}`,
    };
    console.debug('response:', response);
    return response;
  },
});

test('called as expect(value).customMatcher()', async () => {
  expect('foo').customMatcher('foo');
});

test('called as expect.customMatcher()', async () => {
  expect({ custom: 'foo' }).toEqual({
    custom: expect.customMatcher('foo'),
  });
});
$ npx jest equals.test.js
 FAIL  ./equals.test.js
  ✓ called as expect(value).customMatcher() (8ms)
  ✕ called as expect.customMatcher() (7ms)

  ● called as expect.customMatcher()

    expect(received).toEqual(expected)

    Difference:

    - Expected
    + Received

      Object {
    -   "custom": customMatcher<foo>,
    +   "custom": "foo",
      }

      15 |
      16 | test('called as expect.customMatcher()', async () => {
    > 17 |   expect({ custom: 'foo' }).toEqual({
         |                             ^
      18 |     custom: expect.customMatcher('foo'),
      19 |   });
      20 | });

      at Object.toEqual (equals.test.js:17:29)

  console.debug equals.test.js:7
    response: { pass: true, message: 'this.equals is defined' }

  console.debug equals.test.js:7
    response: { pass: false, message: 'this.equals is undefined' }

Note that I added a console.debug() statement because the message from the custom matcher is not actually shown (as discussed in #7492).

Expected behavior

I'd expect this.equals to be defined in both invocations.

Run npx envinfo --preset jest

$ npx envinfo --preset jest
npx: installed 1 in 0.974s

  System:
    OS: Linux 5.0 Arch Linux
    CPU: (4) x64 Intel(R) Core(TM) i5-6360U CPU @ 2.00GHz
  Binaries:
    Node: 11.13.0 - /usr/bin/node
    Yarn: 1.15.2 - /usr/bin/yarn
    npm: 6.9.0 - /usr/bin/npm
  npmPackages:
    jest: ^24.7.1 => 24.7.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions