Angular 单击事件本机元素(锚标记)的单元测试

Angular 单击事件本机元素(锚标记)的单元测试,angular,unit-testing,karma-jasmine,Angular,Unit Testing,Karma Jasmine,我有一些简单的锚标签的网址。测试的目标是当单击链接时,它应该在新选项卡中打开,然后将给定的url与打开的新选项卡url进行比较 我试过用带有窗口对象的spyOn。但我没有成功 这是我试过的 <a href="https://www.google.com/" target="_blank">google</a> import { ComponentFixture, TestBed } from '@angular/core/testing'; import { AppC

我有一些简单的锚标签的网址。测试的目标是当单击链接时,它应该在新选项卡中打开,然后将给定的url与打开的新选项卡url进行比较

我试过用带有窗口对象的spyOn。但我没有成功

这是我试过的

<a href="https://www.google.com/" target="_blank">google</a>


import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('guideline link', () => {
    let comp: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [],
            declarations: [AppComponent],
            providers: [],
        });

        fixture = TestBed.createComponent(AppComponent);

        comp = fixture.componentInstance;
    });

    it('link should be opened in separate tab', async () => {
        fixture.detectChanges();
        spyOn(window, 'open');
        const link = fixture.debugElement.nativeElement.querySelector('a');
        fixture.whenStable().then(() => {
            expect(link).toHaveBeenCalled();
            expect(window.open).toHaveBeenCalledWith('https://www.google.com/');
        });

    });

});

从“@angular/core/testing”导入{ComponentFixture,TestBed};
从“./app.component”导入{AppComponent};
描述('指南链接',()=>{
让comp:AppComponent;
let夹具:组件夹具;
在每个之前(()=>{
TestBed.configureTestingModule({
进口:[],
声明:[AppComponent],
提供者:[],
});
fixture=TestBed.createComponent(AppComponent);
comp=夹具。组件状态;
});
它('链接应在单独的选项卡中打开',异步()=>{
fixture.detectChanges();
spyOn(窗口“打开”);
const link=fixture.debugElement.nativeElement.querySelector('a');
fixture.whenStable()然后(()=>{
expect(link).toHaveBeenCalled();
期望(window.open).已被调用('https://www.google.com/');
});
});
});
面临着类似的问题。 这对我很有用:

  const link = fixture.debugElement.nativeElement.querySelector("a");
  link.click();
他面临着类似的问题。 这对我很有用:

  const link = fixture.debugElement.nativeElement.querySelector("a");
  link.click();

您没有单击代码中的
锚定
标记。那么该如何重定向呢?如果我使用
const link=fixture.debugElement.nativeElement.querySelector('a')。click()您没有单击代码中的
锚定
标记。那么该如何重定向呢?如果我使用
const link=fixture.debugElement.nativeElement.querySelector('a')。click()