Categories
JavaScript Answers

How to use object types with Jasmine’s toHaveBeenCalledWith method with JavaScript?

Spread the love

Sometimes, we want to use object types with Jasmine’s toHaveBeenCalledWith method with JavaScript.

In this article, we’ll look at how to use object types with Jasmine’s toHaveBeenCalledWith method with JavaScript.

How to use object types with Jasmine’s toHaveBeenCalledWith method with JavaScript?

To use object types with Jasmine’s toHaveBeenCalledWith method with JavaScript, we can use spies.

For instance, we write

class Klass {
  method(arg) {
    return arg;
  }
}

describe("spy behavior", () => {
  it("should spy on an instance method of a Klass", () => {
    const obj = new Klass();
    spyOn(obj, "method");
    obj.method("foo argument");
    expect(obj.method).toHaveBeenCalledWith("foo argument");
    expect(
      obj.method.calls.mostRecent().args[0] instanceof String
    ).toBeTruthy();
  });
});

to create the Klass class to test.

Then we create a new Klass instance in the test.

We then spy on the method method with spyOn(obj, "method");.

Next, we call the method with obj.method("foo argument");.

Then we check that obj.method is called with 'foo argument' with expect(obj.method).toHaveBeenCalledWith("foo argument");.

And then we check that it’s most recently called with a string with

expect(obj.method.calls.mostRecent().args[0] instanceof String).toBeTruthy();

Conclusion

To use object types with Jasmine’s toHaveBeenCalledWith method with JavaScript, we can use spies.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *