Skip to content

Better error output for toHaveBeenCalledWith #60

Description

@ericclemmons

First, great project! I'm sure you saw my tweet of praise:

https://twitter.com/ericclemmons/status/681615901343399936

toHaveBeenCalledWith

Anyway, having replaced sinon with this, I've noticed that this very readable call...

expect(this.say).toHaveBeenCalledWith("foo");

...yields an error with only half of the picture. There's no telling what it was called with, or never called at all:

Error: spy was never called with [ 'foo' ]

toEqual

However, explicitly using toEqual is much more useful:

expect(this.say.calls[0].arguments).toEqual(["foo"]);
[
-  "bar"
+  "foo"
]

Proposal

I'd recommend mimicking the output of toEqual.

When the spy was called & matched.

No changes.

(Patch) When the spy was never called.

"say" was never called

(Patch) Show all calls.

"name" was called N times without ["foo"]:

1 with ["bar"]

2 with [undefined]

...

(Breaking Feature) Expect the assertion to always reference the last call (e.g. spy.calls[spy.calls.length -1].

This is a suggestion for a possible future release that's largely unrelated to this issue.

"name" was last called with ["bar"], expected ["foo"].

What I like about this approach is that it works great for repeated assertions:

const query = function(params) {
  return axios.get("/api", { params });
};

var spy = expect.spyOn(axios, "get");

query({ foo: "foo" });
expect(spy).toHaveBeenCalledWith("/api", { foo: "foo" });
query({ bar: "bar" });
expect(spy).toHaveBeenCalledWith("/api", { bar: "bar" });

I only list it here because improving the usability of toHaveBeenCalledWith will lend itself to more use :)


What do you think @mjackson?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions