[英]Checking local variable while unit testing on a component in Angular gives error
假設有 2 個組件:AppComponent 和 TestComponent。 我在 AppComponent 的 HTML 模板中使用它的指令調用 TestComponent。 現在 TestComponent 有一個 @Input() 屬性(讓它成為 myTitle )。
我只對 TestComponent 進行單元測試。 對於標題,我在測試本身中傳遞了一個隨機值。 這是相同的代碼:
app.component.html
<span><app-test [myTitle]="title"></app-test></span>
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
title = {name: 'hello-world'};
}
test.component.html
<p>test works!!{{myTitle.name}}</p>
<button (click)="onClick()">Click Please !!!</button>
測試組件.ts
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit{
@Input() myTitle;
filter;
constructor(){
}
ngOnInit():void{
this.myTitle.name = "Hi!!";
}
onClick(){
this.filter="GokuSSj3";
}
}
test.component.spec.ts
describe('Test component',() =>{
let temp;
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() =>{
TestBed.configureTestingModule({
declarations: [TestComponent],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(()=>{
temp = {name: "Heloooo"};
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should check First',()=>{
component.myTitle = temp;
console.log(component.myTitle.name);
console.log(temp.name);
fixture.detectChanges();
console.log(component.myTitle.name);
console.log(temp.name);
expect(component.myTitle.name).toEqual(temp.name);
});
it('should check whether onClick is called on button click or not and also the value of filter',()=>{
component.myTitle = temp;
spyOn(component,'onClick');
fixture.detectChanges();
let btn = fixture.debugElement.query(By.css('button'));
btn.triggerEventHandler('click',null);
fixture.whenStable().then(()=>{
expect(component.onClick).toHaveBeenCalled();
expect(component.filter).toEqual("GokuSSj3");
});
});
第二個測試用例顯示錯誤:Expected undefined to equal 'GokuSSj3'。 為什么會這樣? 即使 onClick 已被調用。
我是這個社區的新手,所以如果有任何失敗,請幫助我改進問題。
由於您在 onClick function 添加了間諜功能,因此它永遠不會觸發並更新過濾器的值。
您需要刪除該間諜 function 並查看實際值更改。
更改測試如下:
it('should check whether onClick is called on button click or not and also the value of filter', () => { component.myTitle = temp; fixture.detectChanges(); let btn = fixture.debugElement.query(By.css('button')); btn.triggerEventHandler('click', null); fixture.whenStable().then(() => { expect(component.filter).toEqual("GokuSSj3"); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.