Skip to content

StackTrace is cut when nesting matchers #4515

@denniske

Description

@denniske

Do you want to request a feature or report a bug?

Bug

What is the current behavior?

Minimal Repository:
https://github.com/denniske/jest-stacktrace-demo

// greeter.test.js

expect.extend({
    toHaveBeenCalledWithSome: function (received, argument) {
        var a = received.calls.allArgs()[0][0];
        argument(a);
        return {
            message: function () { return ""; },
            pass: true
        };
    }
});

var greeter = {
    welcome: function (name) {
        var action = {
            message: "Hi " + name
        };
        console.log(action);
    }
};

describe("greeter", function () {
    it("'welcome' creates action with welcome message", function () {
        spyOn(console, "log");
        var name = "John";
        greeter.welcome(name);
        expect(console.log).toHaveBeenCalled();
        expect(console.log).toHaveBeenCalledWithSome(function (action) {
            expect(action).toBeTruthy();
            expect(action.message).toContain("Welcome");
            expect(action.message).toContain(name);
            expect(action.message).toBe("Welcome " + name);
        });
    });
});

yarn test will produce the following:

 FAIL  .\greeter.test.js
  ● greeter › 'welcome' creates action with welcome message

    expect(string).toContain(value)

    Expected string:
      "Hi John"
    To contain value:
      "Welcome"

      at Object.<anonymous> (greeter.test.js:25:29)

  greeter
    × 'welcome' creates action with welcome message (7ms)

The error does not occur in greeter.test.js:25, but in greeter.test.js:27.

The problem is that I am using expect statements inside the callback of a custom matcher toHaveBeenCalledWithSome.

This causes the stacktrace to be cut in the outer matcher toHaveBeenCalledWithSome here:
https://github.com/facebook/jest/blob/a397abaf9f08e691f8739899819fc4da41c1e476/packages/expect/src/index.js#L204

What is the expected behavior?

Do not cut the stacktrace such that error is reported correctly at greeter.test.js:27.

I would suggest to only cur stacktrace when error is no JestAssertionError:

if(!(error instanceof JestAssertionError)) {
    Error.captureStackTrace(error, throwingMatcher);
}

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

No jest config, versions are:

Jest - 21.1.0,
Node - 7.10.0
npm - 4.6.1
OS - Windows 10

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