Void 的 Angular 单元测试代码覆盖率:()=>

时间:2020-12-24 16:48:32

标签: angular unit-testing

我的 component.ts 文件中有一个简单的 ngOnInit() 函数,它带有一个 void 类型的 const 变量。有没有人知道如何覆盖那行代码并进入那个 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();
  });
});

1 个答案:

答案 0 :(得分:0)

您可以通过在 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');
  }
}