【发布时间】:2021-07-07 18:00:48
【问题描述】:
我有一个从变量 x 生成变量 y 的场景。我正在尝试为变量 y 编写一个测试用例,该变量 y 是使用 split() 方法从另一个声明的变量 x 生成的。另外,我有一个标志 hasY 是否根据值 y 在 HTML 中显示变量。但是,如果我没有将 flag-hasY 移动到 method-func() 初始化的末尾,测试会由于某种原因失败。
下面是我的组件和测试。我知道问题出在hasY & y 变量上。 If I have a default value for y variable or if I move hasY after y variable declaration the test was a pass. 但是,如果我之前声明 hasY,我不确定为什么会失败。有什么想法吗??
HTML:
<div class="info">
<span>{{x}}</span>
<span *ngIf="hasY">{{y}}</span>
</div>
AppComponent.ts ---> 这里我使用 split() 打破了值
export class AppComponent implements OnInit {
title = 'test';
public value: string = "3.50 cm";
x: string = "";
y: string = "";
hasY: boolean = false;
constructor(){}
ngOnInit(){
this.func()
}
func(){
const values = this.value.split(" ");
this.hasY =
this.y !== undefined &&
this.y !== null &&
this.y.length > 0 &&
this.y.trim().length > 0;
if(values.length<2){return false;}
this.x = values[0];
this.y = values[1];
console.log(values);
}
}
Test.ts --> 这是一个直接的测试。不知道为什么会失败
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents()
.then(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
});;
});
it("test1", () => {
fixture.detectChanges();
const j: DebugElement = fixture.debugElement.query(By.css(".info > span:first-child"));
expect(j).not.toBeNull();
expect(j.nativeElement.textContent.trim()).toEqual("3.50");
const k: DebugElement = fixture.debugElement.query(By.css(".info > span:nth-child(2)"));
expect(k).not.toBeNull();
expect(k.nativeElement.textContent.trim()).toEqual("cm");
});
});
【问题讨论】:
标签: angular unit-testing karma-jasmine