Angular测试用例使用命令npm test Angular项目失败

问题描述 投票:0回答:1

[请帮助我解决有关Angular项目的问题。因为使用npm test运行时,它在我的规格文件中给我错误。

共享我的整个源代码,并弄错了我得到的。

navbar.component.html

<div class="app-navbar">
  <ul>
    <li class="nav-item" *ngFor="let navItem of subsections" [class.active-subsection]="currentSubSection===navItem">
      <a href="javascript:void(0);" (click)="dispatchAction(navItem)">{{navItem}} </a>
    </li>
  </ul>
</div>

navbar.component.ts

import { Component, OnInit } from '@angular/core';
import { Store, select } from '@ngrx/store';

import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import { News } from '../../model/news';

// ngrx store 
import { AppState } from '../../store/reducers';
import { getNewsSection } from '../../store/selectors/news.selectors';
import * as fromActions from '../../store/actions';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})

export class NavbarComponent implements OnInit {
  sectionNews: News[];
  currentSubSection: string;
  subsections: string[] = [];
  unsubscribe: Subject<void> = new Subject();

  constructor(private store: Store<AppState>) { }

  ngOnInit() {
    this.initSubscriptions();
  }

  /**
   * Holding Subscriptions
   */
  initSubscriptions(): void {

    // subscription to store & selector to pull all section news
    this.store.pipe(select(getNewsSection))
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(
        sectionNews => {
          this.currentSubSection = '';
          this.subsections = [];
          for (const item of sectionNews) {
            //pulling all subsection which is unique and non empty
            if (item.subsection.length && !this.subsections.includes(item.subsection)) {
              this.subsections.push(item.subsection);
            }
          }
        }
      );
}
  /**
   * Filter news by dispatching subsection filter action
   * @param filter - subsection string
   */
  dispatchAction(filter: string): void {
    this.currentSubSection = filter;
    this.store.dispatch(new fromActions.FilterSubSection(filter));
  }

}

navbar.component.spec.ts

it('should display subsection in template', async() => {
    // assign mock values to subsections array
    component.subsections = ['movie', 'tech', 'money'];
    // <a> tag in html will contain one of values of subsections array. select the <a> tag using query(By.css())
    const anchorElement = fixture.debugElement.query(By.css('a')).nativeElement.textContent;


    // after assigning values to subsections, detect changes. this is async call.
    fixture.detectChanges();

    expect(component.subsections).toContain(anchorElement);
  });

使用npm测试运行时出错

ERROR: 'Unhandled Promise rejection:', 'Cannot read property 'nativeElement' of null', '; Zone:', 'ProxyZone', '; Task:', 'setTimeout', '; Value:', TypeError{__zone_symbol__currentTask: ZoneTask{zone: Zone{_properties: ..., _parent: ..., _name: ..., _zoneDelegate: ...}, runCount: 0, _zoneDelegates: null, _state: 'notScheduled', type: 'macroTask', source: 'setTimeout', data: Object{handleId: ..., isPeriodic: ..., delay: ..., args: ...}, scheduleFn: function scheduleTask(task) { ... }, cancelFn: null, callback: function () { ... }, invoke: function () { ... }}}, 'TypeError: Cannot read property 'nativeElement' of null

ERROR: 'Unhandled Promise rejection:', 'Cannot read property 'triggerEventHandler' of null', '; Zone:', 'ProxyZone', '; Task:', 'setTimeout', '; Value:', TypeError{__zone_symbol__currentTask: ZoneTask{zone: Zone{_properties: ..., _parent: ..., _name: ..., _zoneDelegate: ...}, runCount: 0, _zoneDelegates: null, _state: 'notScheduled', type: 'macroTask', source: 'setTimeout', data: Object{handleId: ..., isPeriodic: ..., delay: ..., args: ...}, scheduleFn: function scheduleTask(task) { ... }, cancelFn: null, callback: function () { ... }, invoke: function () { ... }}}, 'TypeError: Cannot read property 'triggerEventHandler' of null
    at Object.click (http://localhost:9876/_karma_webpack_/webpack:/testing/index.ts:39:8)
    at Object.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/components/navbar/navbar.component.spec.ts:62:5)
    at step (http://localhost:9876/_karma_webpack_/main.bundle.js:257:23)
    at Object.next (http://localhost:9876/_karma_webpack_/main.bundle.js:238:53)
    at http://localhost:9876/_karma_webpack_/main.bundle.js:232:71
    at new ZoneAwarePromise (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:729:1)
    at webpackJsonp../src/app/components/navbar/navbar.component.spec.ts.__awaiter (http://localhost:9876/_karma_webpack_/main.bundle.js:228:12)
    at Object.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/components/navbar/navbar.component.spec.ts:57:65)
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:334:1)

这些错误,请帮助解决并提出解决该问题的建议。

我也可以共享我的包json文件。请指导我,因为我是这个领域的新手。我正在运行所有一项npm测试,并且以上错误即将到来。这个spec文件在项目中。我没有写这个。我只是试图执行测试用例。有关更多信息,请回复帮助和帮助。

angular testing karma-runner
1个回答
0
投票
const anchorElement = fixture.debugElement.query(By.css('a'))

该语句返回null。由于该调用是异步的,因此仅当子节有数据时,您才需要添加检查以呈现html。

<div class="app-navbar">
  <ul *ngIf="subsections.length>0">
    <li class="nav-item" *ngFor="let navItem of subsections" [class.active-subsection]="currentSubSection===navItem">
      <a href="javascript:void(0);" (click)="dispatchAction(navItem)">{{navItem}} </a>
    </li>
  </ul>
</div>


it('should display subsection in template', async() => {
    // assign mock values to subsections array
    component.subsections = ['movie', 'tech', 'money'];
    // <a> tag in html will contain one of values of subsections array. select the <a> tag using query(By.css())
    fixture.detectChanges();
    const anchorElement = fixture.debugElement.query(By.css('a')).nativeElement.textContent;
    expect(component.subsections).toContain(anchorElement);
  });
© www.soinside.com 2019 - 2024. All rights reserved.