使用 *ngFor 和 Input 运行单元测试



我是Angular的新手。我创建了一个使用 *ngFor 显示按钮的组件。

TS 文件:

import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'display-button',
templateUrl: './display-button.component.html',
styleUrls: ['./display-button.component.scss']
})
export class DisplayButtonComponent implements OnInit {
@Input() compInput: any;
buttons: any;
constructor() { }
ngOnInit() {
if (this.compInput) {
this.buttons = this.compInput.scriptButtonData.buttons;
}
}
buttonClicked(selectedValue) {
//do something
}
}
}

html 文件:

<button class="scriptButton" *ngFor="let button of buttons" (click)="buttonClicked(button.value)" >{{button.name}}</button>

规范文件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { InlineScriptButtonComponent } from './display-button.component';
import {By} from '@angular/platform-browser';
describe('DisplayButtonComponent', () => {
let component: DisplayButtonComponent;
let fixture: ComponentFixture<DisplayButtonComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DisplayButtonComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DisplayButtonComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should contain label', () => {
component.compInput= {
scriptButtonData: {
type: "scriptButton",
buttons: [
{
name: "Proceed",
value: "Yes"
},
{
name: "Cancel",
value: "No"
},
]
},
someOtherProperty: null,
};
fixture.detectChanges();
let buttonLabels = fixture.debugElement.queryAll(By.css('scriptButton'));
expect( buttonLabels.length).toBe(2);
});
});

我正在编写单元测试来测试是否显示 2 个按钮。当我运行测试时,它失败了,因为buttonLabels.length为0。即使我在测试中初始化输入变量 compInput,当它遇到该行时似乎为空

if (this.compInput) {

为什么这为空?我做错了什么? 此外,作弊的一种方法是以这种方式初始化测试:

component.buttons = [
{
name: "Proceed",
value: "Yes"
},
{
name: "Cancel",
value: "No"
},
]

虽然测试通过添加上述行通过,但这是作弊,因为我没有测试 ngOnInit 函数中的代码。

为什么我设置的值 component.compInput 对测试不可用。测试此功能的正确方法是什么?

从测试中调用 ngOnInit((,否则在设置 component.compInput 之前完成。 同时查找 document.getElementsByClass('scriptButton'( 来获取您的元素。

我也不会直接从你的 ngOnInit(( 调用你的 if 语句,而是把它放在一个从 ngOnInit(( 调用的方法中。这是我个人喜欢的风格,使生命周期钩子更干净。

这是您的适合声明,其中包含更新。

fit('should contain label', () => {
component.compInput = {
scriptButtonData: {
type: 'scriptButton',
buttons: [
{
name: 'Proceed',
value: 'Yes'
},
{
name: 'Cancel',
value: 'No'
}
]
},
someOtherProperty: null
};
component.ngOnInit();  //need to invoke ngOnInit()
fixture.detectChanges();
let buttonLabels = document.getElementsByClassName('scriptButton');
expect(buttonLabels.length).toBe(2);
});

您指定了错误的CSS类,因此找不到该类的任何按钮。

最新更新