Stubbing behavior with td.when()
mainUse td.when() to define how a test double should behave when it is called. This allows you to stub specific return values, exceptions, or side effects based on the arguments passed to the double.
Key stubbing patterns include:
- Argument matching: You can stub specific arguments, no arguments, or use matchers to loosen constraints.
- Sequential returns: Stubbing multiple consecutive calls to return different values.
- Callbacks: Stubbing APIs that rely on callback functions.
- Exceptions: Using
thenThrow()to simulate errors. - Promises: Using
thenResolve()orthenReject()to simulate asynchronous behavior. - Side effects: Using
thenDo()to execute custom logic when the stub is called.