In Angular project (Angular CLI: 9.1.4) I have a component with has function using window.location.href = EXTERNAL_URL
a.component.ts
import { Component, OnInit } from '@angular/core';
import { Service } from 'services/service';
@Component({
selector: 'a',
templateUrl: './a.component.html',
styleUrls: ['./a.component.scss']
})
export class AComponent implements OnInit {
constructor(private service: Service) {}
ngOnInit(): void {}
redirect() {
window.location.href = 'https://sample.com'
}
}
For unit test, I have a.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AComponent } from './A.component';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
describe('#AComponent', () => {
let component: AComponent;
let fixture: ComponentFixture<AComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule],
declarations: [AComponent]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
describe('test', () => {
it('test redirect function', () => {
component.redirect();
expect(window.location.href).toEqual('https://sample.com');
});
});
});
it must check the URL 'window.location.href' is same as I expected.
But when running test, showed error which says
Expected 'http://localhost:0987/context.html' to equal 'https://sample.com'
Why window.location.href param is like this?
Also, Karma (v5.0.4) showed test result on browser normally, but on this test, browser page is suddenly changed.
It happens because 'window.location.href' had run on test browser( it tried to open https://sample.com). But because of this redirection, I cannot see Karma result.
So, my question is
- How can I test window.location.href
- How can I stop redirection on karma test browser
P.S. I had thought that using window.location.href was not good, but I couldn't find any ways to redirect external URL.
need to test everything except the actual setting of window.location.href -
. Maybe I don't need to testwindow.location.href
itself. I'll remove this test( still, I wonder if I could solve the second question; stop redirection ...). Thank you – Iover