检查元素是否存在 - Jasmine&角

时间:2018-03-01 16:06:59

标签: angular jasmine

我想编写一个测试来检查点击后页面上是否存在元素。因此,当我单击带有“addItem”类的元素时,使用* ngIf隐藏此元素。我试过这样的话:

it('Should handle click on .addItem button', () => {
    spyOn(component, 'addItem');
    addItemDebugElement = componentFixture.debugElement.query(By.css('.addItem'));
    addItemDebugElement.nativeElement.click();  //  click on the button
    expect(addItemDebugElement).toExist();
});

但它说:Property 'toExist' does not exist on type 'Matchers<DebugElement>'. 你能告诉我怎么做吗?非常感谢!

3 个答案:

答案 0 :(得分:1)

你可以试试这个来检查元素是否存在于Dom

expect($(document)).toContain(addItemDebugElement)

expect(addItemDebugElement).toBeInDom();

答案 1 :(得分:1)

我建议你使用

//    Add Item Debug Ele comes out as null.
addItemDebugElement = componentFixture.debugElement.query(By.css('.addItem'));
expect(addItemDebugElement).toBeFalsy();

和...

//    Add Item Debug Ele comes out as not null.
addItemDebugElement = componentFixture.debugElement.query(By.css('.addItem'));
expect(addItemDebugElement).toBeTruthy();

答案 2 :(得分:0)

这是适用于我的解决方案:

it('Should handle click on .addItem button', () => {
 spyOn(component, 'addItem');
 const fixture = TestBed.createComponent(AppComponent);

 addItemDebugElement = fixture.debugElement.query(By.css('.addItem'));


 addItemDebugElement.nativeElement.click(); 

 expect(fixture.debugElement.nativeElement).toContain(addItemDebugElement);  

});