jasmine-auto-spies
Create automatic spies from classes in jasmine tests.
If you're using TypeScript it'll also create auto spies for Promise or Observable returning methods and provide type completion.
What is it good for?
Installation
npm install -D jasmine-auto-spies
Setup
In your tsconfig.json
set these 2 flags -
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
}
}
Usage
1. Spying on regular sync methods
Let's say you have a class -
class MyService{
getName(): string{
return 'Bonnie';
}
}
This is how you create an automatic spy for it -
import { Spy, createSpyFromClass } from 'jasmine-auto-spies';
let myServiceSpy: Spy<MyService>;
beforeEach( ()=> {
myServiceSpy = createSpyFromClass( MyService );
});
it( ()=> {
myServiceSpy.getName.and.returnValue('Fake Name');
... (the rest of the test) ...
});
2. Spy on a Promise
returning method
First, annotate the method with @AsyncSpyable
-
import { AsyncSpyable } from 'jasmine-auto-spies';
export class MyService{
@AsyncSpyable()
getItems(): Promise<any> {
return Promise.resolve( itemsList );
}
}
Now you can use the resolveWith
or rejectWith
methods -
import { Spy, createSpyFromClass } from 'jasmine-auto-spies';
let myServiceSpy: Spy<MyService>;
beforeEach( ()=> {
myServiceSpy = createSpyFromClass( MyService )
});
it( ()=>{
myServiceSpy.getItems.and.resolveWith( fakeItemsList );
myServiceSpy.getItems.and.rejectWith( fakeError );
});
3. Spy on a Observable
returning method
First, annotate your Observable returning method with @AsyncSpyable
-
import { AsyncSpyable } from 'jasmine-auto-spies';
export class MyService{
@AsyncSpyable()
getProducts(): Observable<any> {
return Observable.of( productsList );
}
}
Now you can use the nextWith
or nextWithError
methods -
import { Spy, createSpyFromClass } from 'jasmine-auto-spies';
let myServiceSpy: Spy<MyService>;
beforeEach( ()=> {
myServiceSpy = createSpyFromClass( MyService )
});
it( ()=>{
myServiceSpy.getProducts.and.nextWith( fakeProductsList);
myServiceSpy.getProducts.and.nextWithError( fakeError );
});
Manual Setup
If you need to manually configure async methods by names you could pass them as arrays of strings -
let spy = createSpyFromClass(
MyClass,
['promiseMethod1', 'promiseMethod2'],
['observableMethod1', 'observableMethod2']
);