I have written test cases for one my component. It's covering the whole function but throws these errors:
Disconnected , because no message in 30000 ms.
OR
Some of your tests did a full page
header.component.ts
import { Component, OnInit } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
constructor(private cookieService:CookieService) {}
ngOnInit(): void {}
logout(): void {
localStorage.clear();
sessionStorage.clear();
let cookie:any = this.cookieService.getAll();
Object.keys(cookie)?.forEach((res:any) => {
this.cookieService.delete(res, '/', '', true, 'None');
document.cookie = `${res}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
});
window.location.href ='https://demo.demopreview.com/login/login.htm';
}
}
header.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HeaderComponent } from './header.component';
import { HttpClientModule } from '@angular/common/http';
import { CookieService } from 'ngx-cookie-service';
describe('HeaderComponent', () => {
let component: HeaderComponent;
let fixture: ComponentFixture<HeaderComponent>;
let cookieService: CookieService;
const mockWindow = { location: { href: '' } };
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [HeaderComponent],
imports:[HttpClientModule],
providers: [
CookieService,
{ provide: 'Window', useValue: mockWindow }
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
cookieService = TestBed.inject(CookieService);
});
afterEach(() => {
localStorage.clear();
sessionStorage.clear();
document.cookie.split(";").forEach((c) => {
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
});
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call cookieService.delete for each cookie', () => {
spyOn(cookieService, 'getAll').and.returnValue({ 'testCookie1': 'value1', 'testCookie2': 'value2' });
spyOn(cookieService, 'delete');
component.logout();
expect(cookieService.delete).toHaveBeenCalledWith('testCookie1', '/', '', true, 'None');
expect(cookieService.delete).toHaveBeenCalledWith('testCookie2', '/', '', true, 'None');
});
});
Its' not related any version issues. Beacause if I remove this test case every test cases passes.
If you must test code that involves direct manipulation of window.location.href
, you may need to adopt a different strategy
In your AppModule, provide the window object as a value. This will allow you to inject it wherever needed.
app.module.ts:
@NgModule({
providers: [
{ provide: 'Window', useValue: window }
]
})
export class AppModule {}
In your HeaderComponent, inject the window object using the 'Window' token. instead of referencing window object directly
header.component.ts
constructor(private cookieService:CookieService,@Inject('Window') private window: Window ) {}
logout(): void {
localStorage.clear();
sessionStorage.clear();
let cookie:any = this.cookieService.getAll();
Object.keys(cookie)?.forEach((res:any) => {
this.cookieService.delete(res, '/', '', true, 'None');
document.cookie = `${res}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
});
this.window.location.href ='https://demo.demopreview.com/login/login.htm';
}
The logout method is asynchronous. To handle asynchronous code in Angular tests, you should use the async and fakeAsync functions provided by Angular testing utilities.
header.component.spec.ts
it('should call cookieService.delete for each cookie', fakeAsync(() => {
spyOn(cookieService, 'getAll').and.returnValue({ 'testCookie1': 'value1', 'testCookie2': 'value2' });
spyOn(cookieService, 'delete');
component.logout();
// Simulate the passage of time until all asynchronous activities complete
tick();
expect(cookieService.delete).toHaveBeenCalledWith('testCookie1', '/', '', true, 'None');
expect(cookieService.delete).toHaveBeenCalledWith('testCookie2', '/', '', true, 'None');
}));