【问题标题】:How to test [routerLink] values rendered from Angular component string array?如何测试从 Angular 组件字符串数组呈现的 [routerLink] 值?
【发布时间】:2021-08-03 16:52:04
【问题描述】:

我需要测试从我的 Angular 组件的字符串数组呈现的 [routerLink] 值。

这是 TypeScript 文件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  title: string = 'Blog App';
  links = [
    { name: 'Home', route: '/home' },
    { name: 'Blog', route: '/blog' },
    { name: 'Create article', route: '/create' }
  ];

  constructor() { }

  ngOnInit(): void {
  }

}

这是 HTML 文件:

<header id="header">
    <div class="center">
      <div id="logo">
        <img src="assets/images/angular.svg" class="app-logo" alt="angular-logo" />
        <span id="brand">
          <strong>{{title}}</strong>
        </span>
      </div>
        <nav id="menu">
            <ul>
                <li *ngFor="let link of links">
                    <a [routerLink]="[ link.route ]" [routerLinkActive]="['active']">{{ link.name }}</a>
                </li>
            </ul>
        </nav>
        <div class="clearfix"></div>
    </div>
</header>

这是测试:

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { HeaderComponent } from './header.component';

describe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ HeaderComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(HeaderComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  
  it('should have nav links href equal to /home, /blog and /create', () => {
    const linksRoute = ['/home', '/blog', '/create'];
    document.querySelectorAll("nav#menu ul > li > a").forEach((el, i) => {
      expect(el.getAttribute('href')).toEqual(linksRoute[i]);
    });
  });
});

我得到的结果:

Expected result of test

【问题讨论】:

    标签: javascript angular testing karma-jasmine


    【解决方案1】:

    您没有收到此错误吗?我想你会收到一个错误,因为 TestBed 模块不知道 routerLink 是什么。

    我会这样做:

    import { Router } from '@angular/router';
    import { RouterTestingModule } from '@angular/router/testing';
    import { By } from '@angular/platform-browser';
    ....
    
    describe('HeaderComponent', () => {
      let component: HeaderComponent;
      let fixture: ComponentFixture<HeaderComponent>;
      // declare router
      let router: Router;
      // we will make sure navigateSpy is called
      let navigateSpy: jasmine.Spy;
    
      beforeEach(async () => {
        await TestBed.configureTestingModule({
          // import RouterTestingModule so routerLinks means something 
          // and do not error out
          imports: [RouterTestingModule],
          declarations: [ HeaderComponent ]
        })
        .compileComponents();
      });
    
      beforeEach(() => {
        // get a handle on the router
        router = TestBed.inject(Router);
        // assign navigateSpy to router.navigate
        navigateSpy = spyOn(router, 'navigate');
        fixture = TestBed.createComponent(HeaderComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
      
      it('should navigate to accurate links', () => {
        const linksRoute = ['/home', '/blog', '/create'];
        // I like using debugElement to query the DOM/HTML
        const links = fixture.debugElement.queryAll(By.css('nav#menu ul > li > a'));
        // check after clicking the link that router.navigate was called accurately
        links.forEach((link, i) => {
           const element = link.nativeElement;
           element.click();
           expect(navigateSpy).toHaveBeenCalledWith([linksRoute[i]]);
        });
      });
    });
    
    
    

    【讨论】:

    • 感谢您的回复@AliF50,但是当我运行您的测试时,Jasmine 给了我一个错误。 ``` 预期的间谍导航已被调用:[ [ 'home' ] ] 但它从未被调用。 ```
    • 好的,抱歉。我在想routerLink 没有绑定到router.navigate,所以它不会被调用。尝试运行您的测试(您拥有的测试),看看它是否通过。
    猜你喜欢
    • 2017-01-27
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 2017-08-29
    • 2018-05-22
    • 2020-06-11
    • 2022-08-24
    • 2016-07-28
    相关资源
    最近更新 更多