I have an issue trying to test the removal of a cookie using a directive.
My directive is the following one:
import { Directive, HostListener } from '@angular/core';
import { CookieService } from 'angular2-cookie/core';
@Directive({
selector: '[appCloseWindow]'
})
/**
* Directive that when we close the window, removes the cookie
*/
export class CloseWindowDirective {
constructor( private readonly _cookieService: CookieService ) { }
@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event: Event) {
const cookie = this._cookieService.get('RandomCookie');
if ( cookie !== undefined ) {
this._cookieService.remove('RandomCookie');
}
}
}
So in the test my problem is that I am not able to reach the remove part, and dont know how to do it.
My test right now is this, I am new doing Tests with Jasmine so probably are wrong...
import { TestBed, async } from '@angular/core/testing';
import { CloseWindowDirective } from './close-window.directive';
import { CookieService } from 'angular2-cookie';
fdescribe('Directive: CloseWindow', () => {
const service = new CookieService;
const directive = new CloseWindowDirective(new CookieService);
beforeEach(async(() => {
spyOn(directive, 'beforeunloadHandler').and.callThrough();
spyOn(service, 'get').and.returnValue('cookieTest');
spyOn(service, 'remove').and.callThrough();
TestBed.configureTestingModule({
providers: [CookieService],
declarations: [CloseWindowDirective]
})
.compileComponents();
}));
it('should create an instance', () => {
expect(directive).toBeTruthy();
});
it('should call directive method', () => {
directive.beforeunloadHandler(new Event('beforeunload'));
expect(directive.beforeunloadHandler).toHaveBeenCalled();
});
it('should call remove the cookie', () => {
const cookie = service.get('testCookie');
service.remove(cookie);
expect(service.remove).toHaveBeenCalled();
});
});
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire