【发布时间】: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