【问题标题】:unit test for click event native element (anchor tag)点击事件原生元素(锚标记)的单元测试
【发布时间】:2019-02-26 13:38:20
【问题描述】:

我有一些带有一些网址的简单锚标记。测试的目标是当点击链接时它应该在新标签中打开,然后将给定的 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/');
        });

    });

});

【问题讨论】:

  • 您没有单击代码中的 anchor 标记。那将如何重定向?
  • 如果我做const link = fixture.debugElement.nativeElement.querySelector('a').click();

标签: angular unit-testing karma-jasmine


【解决方案1】:

面临类似的问题。 这对我有用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-10
    • 2017-02-26
    • 1970-01-01
    • 2016-09-18
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多