Here is a snippet of functional TypeScript code along with its test:
menu.service.ts:
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
export class MenuService {
private events = new Subject();
public subscribe(next): Subscription {
return this.events.subscribe(next);
}
public next(event?): void {
this.events.next(event);
}
}
menu.service.spec.ts:
import { MenuService } from './menu.service';
describe('MenuService', () => {
let menuService: MenuService;
beforeEach(() => {
menuService = new MenuService();
});
it('should call a subscriber when an event is fired', function() {
const subscriber = jasmine.createSpy('subscriber');
menuService.subscribe(subscriber);
menuService.next();
expect(subscriber).toHaveBeenCalled();
});
});
Currently, I am updating my documentation and coding standards by adding types. I have made changes to the service like so:
import { Observer } from 'rxjs/Observer';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
export class MenuService {
private events = new Subject();
/**
* Subscribe to events when the menu opens.
*
* @param next The callback for the subscription.
* @returns The subscription for the event.
*/
public subscribe(next: Observer<null>): Subscription {
return this.events.subscribe(next);
}
public next(event?): void {
this.events.next(event);
}
}
However, after this update, TypeScript is now not allowing me to pass a spy. I tried using a Function
instead, but it led to type errors on this.events.subscribe
. How can I resolve this issue?
edit
The error message I am getting is:
Argument of type 'Spy' is not assignable to parameter of type 'Observer<null>'. at line 14 col 31
Property 'next' is missing in type 'Spy'.