Categories
JavaScript Answers

How to stub a method of Jasmine mock object with JavaScript?

Spread the love

Sometimes, we want to stub a method of Jasmine mock object with JavaScript.

In this article, we’ll look at how to stub a method of Jasmine mock object with JavaScript.

How to stub a method of Jasmine mock object with JavaScript?

To stub a method of Jasmine mock object with JavaScript, we can use the callFake method.

For instance, we write

const someObject = jasmine.createSpyObj("someObject", ["method1", "method2"]);

const error = new Error("an-exception");
someObject.method1.and.callFake(() => {
  throw error;
});
expect(yourFncCallingMethod1).toThrow(error);

to call createSpyObj to create a spy object.

Then we call someObject.method1.and.callFake with a function with the mocked implementation of method1.

Then we check that the yourFncCallingMethod1 function which calls method1 to throw an error.

Conclusion

To stub a method of Jasmine mock object with JavaScript, we can use the callFake method.

Conclusion

To stub a method of Jasmine mock object with JavaScript, we can use the callFake method.

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 *