Search⌘ K
AI Features

Spy Strategies

Explore how to implement and customize spy strategies in Jasmine to control method calls during Angular unit testing. Understand default stub behavior, use callFake and returnValue for flexible mocks, and apply custom spy strategies to reduce repetitive test code. This lesson helps you write more maintainable and effective tests by mastering spy behaviors.

When we set up a spy in Jasmine, it can respond to method calls in a number of ways. The default behavior is to use the stub method, which will do nothing. We also have a few other options available:

  • We can use callFake to provide a callback that will be fired instead of the real method.

  • We can use callThrough to pass the method call on to the original object that we are spying on.

  • We can specify a value to be returned using the returnValue or returnValues method.

  • We can use the throwError to throw an error if the method is called. We could use this if we want to make certain that a specific method on the spy is never called.

Set up a custom spy strategy

When we use ...