在 Angular 项目(Angular CLI:9.1.4)中,我有一个使用 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'
}
}
对于单元测试,我有一个.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');
});
});
});
它必须检查 URL 'window.location.href' 是否与我预期的相同。
但是在运行测试时,显示错误
<块引用>预期“http://localhost:0987/context.html”等于“https://sample.com”
为什么 window.location.href 参数是这样的?
此外,Karma (v5.0.4) 在浏览器上正常显示测试结果,但在此测试中,浏览器页面突然发生变化。
这是因为'window.location.href'在测试浏览器上运行(它试图打开https://sample.com)。但是由于这种重定向,我看不到 Karma 结果。
所以,我的问题是
附言我原以为使用 window.location.href 不好,但是我找不到任何重定向外部 URL 的方法。