Skip to content

toHaveBeenNthCalledWith has a wrong test report when using objectsΒ #6614

@maximelebastard

Description

@maximelebastard

πŸ› Bug Report

When used with objects or classes for parameters expectations, toHaveBeenNthCalledWith error messages report the wrong call argument. It reports the last call arguments as received arguments.

To Reproduce

This test using expect.toHaveBeenNthCalledWith with objects has a false failure report

class Bar {
  constructor(toto) {
    this.toto = toto;
  }
}

function foo(mock) {
  mock.titi(new Bar('a'));
  mock.titi(new Bar('not b at all'));
  mock.titi(new Bar('c'));
}
test('toHaveBeenNthCalledWith bad report', () => {
  const mock = {
    titi: jest.fn()
  };

  foo(mock);

  expect(mock.titi).toHaveBeenNthCalledWith(1, new Bar('a'));
  expect(mock.titi).toHaveBeenNthCalledWith(2, new Bar('b'));
  expect(mock.titi).toHaveBeenNthCalledWith(3, new Bar('c'));
});

The test fails because the second mock.titi call received new Bar('not b at all') instead of new Bar('b') as a parameter.
But the error messages says it was called with new Bar('c') which is the last call.

  ● toHaveBeenNthCalledWith bad report

    expect(jest.fn()).toHaveBeenNthCalledWith(expected)

    Expected mock function second call to have been called with:
      {"toto": "b"}
    as argument 1, but it was called with
      {"toto": "c"}.

    Difference:

    - Expected
    + Received

      Bar {
    -   "toto": "b",
    +   "toto": "c",
      }

      18 |
      19 |   expect(mock.titi).toHaveBeenNthCalledWith(1, new Bar('a'));
    > 20 |   expect(mock.titi).toHaveBeenNthCalledWith(2, new Bar('b'));
         |                     ^
      21 |   expect(mock.titi).toHaveBeenNthCalledWith(3, new Bar('c'));
      22 | });
      23 |

      at Object.<anonymous>.test (src/report.test.js:20:21)

Expected behavior

I expect the test report to give the real argument the mock was called with.

Run npx envinfo --preset jest

npx envinfo --preset jest
npx: installed 1 in 1.606s

  System:
    OS: macOS High Sierra 10.13.4
    CPU: x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
  Binaries:
    Node: 8.10.0 - /usr/local/bin/node
    Yarn: 1.5.1 - /opt/local/bin/yarn
    npm: 6.1.0 - /usr/local/bin/npm
  npmPackages:
    jest: ^23.0.1 => 23.0.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions