From 9fad81f8d000827fde2c6d760ae1d20913c94ac8 Mon Sep 17 00:00:00 2001 From: Shai Reznik Date: Sat, 5 Sep 2020 14:28:55 +0300 Subject: [PATCH] docs(createfunctionspy): add documentation for createFunctionSpy --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/README.md b/README.md index 4bc296e..be48a3c 100644 --- a/README.md +++ b/README.md @@ -342,3 +342,51 @@ MyClass{ }) ``` + +### 9. Spying on a function + +You can create an "auto spy" for a function using: + +```ts +import { createFunctionSpy } from 'jasmine-auto-spies'; + +describe('Testing a function', () => { + it('should be able to spy on a function', () => { + function addTwoNumbers(a, b) { + return a + b; + } + + const functionSpy = createFunctionSpy('addTwoNumbers'); + + functionSpy.and.returnValue(4); + + expect(functionSpy()).toBe(4); + }); +}); +``` + +This is useful if you have an observable returning function and you want to use `nextWith` for example: + +```ts +import { createFunctionSpy } from 'jasmine-auto-spies'; +import { Observable, of } from 'rxjs'; +import { ObserverSpy } from '@hirez_io/observer-spy'; + +describe('Testing an observable function', () => { + it('should be able to spy on observable', () => { + function getResultsObservable(): Observable { + return of(1, 2, 3); + } + + const functionSpy = createFunctionSpy( + 'getResultsObservable' + ); + + functionSpy.and.nextWith(4); + const observerSpy = new ObserverSpy(); + functionSpy.subscribe(observerSpy); + + expect(observerSpy.getLastValue()).toBe(4); + }); +}); +```