单元测试ngOnInit()中的变量声明

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

我正在尝试提高TDD的技能,并且我再次在Angular中可以遵循的所有教程。但是这次尝试对它们进行100%代码覆盖率的单元测试。

我有一个愚蠢的问题,我无法在the documentation中找到答案。也无法在Stackoverflow中找到那么简单的问题。

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, interval, Subscription } from 'rxjs/';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

  secondes: number;
  counterSubscritpion: Subscription;

  ngOnInit() {
    const counter = interval(1000);
    const dummy = 'foo';

    this.counterSubscritpion = counter.subscribe(
      (value) => {
        this.secondes = value;
    });
  }

  ngOnDestroy() {
    this.counterSubscritpion.unsubscribe();
  }

我的模板当然很简单:

<p> nothing should appear here : {{dummy}} </p>
<p> whereas here should be {{secondes}} secondes </p>

所以阅读文档将帮助我测试secondescounterSubscritpion ...

但是我如何测试counterdummy及其值已被声明?因为Karma的测试覆盖率报告告诉我,我应该测试`interval(1000)调用

到目前为止,我对此仍然感到困惑:

  let fixture: ComponentFixture<AppComponent>;
  let routerOutlet: any;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent]
    });
    fixture = TestBed.createComponent(AppComponent);
  });

  it ('should declare dummy variable', () => {
    const appComp = new AppComponent();
    appComp.ngOnInit();
    // and so what ???
  });
angular unit-testing jasmine karma-runner
1个回答
1
投票

首先,您正在使用TestBed创建AppComponentTestBed配置并创建一个test context。可以创建路线,服务等。

但是您没有在it中使用它。要通过TestBed获取创建的组件,可以调用TestBed.get(AppComponent)进行检索。

TestBed之外(即new创建外部组件时),您将无法访问组件的模板。尽管在某些情况下它可能很有用,但对于您而言可能并非如此。

  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent]
    });
    fixture = TestBed.createComponent(AppComponent);
  });

  beforeEach(() => {
    component = TestBed.get(AppComponent);
  });

  it ('should create', () => {
    expect(component).toBeTruthy();
  });

  ...

要测试异步机制,请阅读https://codecraft.tv/courses/angular/unit-testing/asynchronous/#_code_async_code_and_code_whenstable_codehttps://codecraft.tv/courses/angular/unit-testing/asynchronous/#_code_async_code_and_code_whenstable_code。归结为asyncfakeAsync

© www.soinside.com 2019 - 2024. All rights reserved.