jest: Incorrect custom async matcher error message

🐛 Bug Report

Custom async matchers are throwing with an error message prefixed with Error and not showing the source code of where the error originated from.

To Reproduce

Given the example in the docs, I get the following output:

expect.extend({
  async toBeDivisibleByExternalValue(received) {
    const externalValue = await Promise.resolve(1000);
    const pass = received % externalValue == 0;
    if (pass) {
      return {
        message: () =>
          `expected ${received} not to be divisible by ${externalValue}`,
        pass: true,
      };
    } else {
      return {
        message: () =>
          `expected ${received} to be divisible by ${externalValue}`,
        pass: false,
      };
    }
  },
});

test('is divisible by external value', async () => {
  await expect(100).toBeDivisibleByExternalValue();
  await expect(101).not.toBeDivisibleByExternalValue();
});
screen shot 2018-09-28 at 18 17 24

Expected behaviour

A pointer to the source and the message highlighted correctly.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 1
  • Comments: 17 (16 by maintainers)

Most upvoted comments

@SimenB Yes, I was able to make it work. I just have a couple of failing snapshots to update. I’m hoping to have the PR today or tomorrow.

@SimenB Thanks for the recommendation! 🙂 I just opened PR #7652 and also kept the refactoring to a minimum. (I’ll open a separate PR for the refactor once we merge this one.) I left a question for you regarding removing a couple of lines from the stack trace.

Great! 🙂 I did manage to figure out how to fix the problem. I’m just trying to get the initial test run to pass before I dive in to start implementing my own test.

The problem is due to us losing the context of the current stack when we create the error here:https://github.com/facebook/jest/blob/6cc2a85621cac07387e82811a6cbe1222c3f449b/packages/expect/src/index.js#L263 The error is being created after the promise resolves here, by which point the previous stack has been discarded: https://github.com/facebook/jest/blob/6cc2a85621cac07387e82811a6cbe1222c3f449b/packages/expect/src/index.js#L307

I’m going to try to try to get the tests passing on my machine in the morning and hopefully open a PR.

I’ll try tomorrow.

If you think errors can be documented/made clearer I’d be happy to do so! It’s really quite straightforward, so I feel any confusion on the traces is a failure on my part in writing grokkable code…