【问题标题】:Angular Unit Testing Code Coverage for Void: ()=>Void 的 Angular 单元测试代码覆盖率:()=>
【发布时间】:2020-12-24 16:48:32
【问题描述】:

我的 component.ts 文件中有一个简单的 ngOnInit() 函数,其 const 变量类型为 void。有没有人知道如何覆盖那行代码并进入那个 void 方法?

app.component.ts

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

export type SessionHandler = ()=> void;

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

export class AppComponent implements OnInit {

  title = 'test';

  constructor(@Inject(DOCUMENT) private _document: any){}

  ngOnInit() {
   const sess: SessionHandler = (): void =>{
     console.log('Meoww');
   }
   this.testService.func(sess);
  }
  }

app.component.spec.ts

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

fdescribe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
  }));

  it('should render title', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    component.ngOnInit();
  });
});

【问题讨论】:

  • 请在问题中提供minimal reproducible example 的组件和测试,作为文本
  • 当我尝试调用 ngOnInit() 方法时。它没有进入上图中提到的 void() 函数
  • 为什么会这样?那只是一个本地定义的函数,没有人调用它(然后它超出范围,没有任何can)。
  • 你能告诉我如何打电话给它并得到覆盖吗?
  • 删除它 - 正如所写,它毫无意义。您定义了一个从未使用过的函数。

标签: angular unit-testing


【解决方案1】:

您可以通过在 onInit() 本身中调用该 void 函数来覆盖该函数,然后编写您对 onInit() 方法调用的期望。 IMO,你应该在 onInit() 之外有这个 void 函数,你可以在 onInit 内部调用它以便于测试。

export class AppComponent implements OnInit {

  title = 'test';

  constructor(@Inject(DOCUMENT) private _document: any){}

  ngOnInit() {
     this.sess();
  }
  sess: SessionHandler = (): void => {
     console.log('Meoww');
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 2010-10-14
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2013-04-16
    相关资源
    最近更新 更多