Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element exists - Jasmine & Angular

I want to write a test to check if an element exists on the page after I click on it. So when I click on the element with the class "addItem", this element is hidden using an *ngIf. I tried it like this:

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();
});

but it says: Property 'toExist' does not exist on type 'Matchers<DebugElement>'. Can you please advise how to do this? Many thanks!

like image 814
decebal Avatar asked Mar 01 '18 16:03

decebal


People also ask

How do I get HTML element in Jasmine?

JASMINE V2.0+ var dummyElement = document. createElement('div'); document. getElementById = jasmine. createSpy('HTML Element').

What is fixture DebugElement?

DebugElement is an Angular class that contains all kinds of references and methods relevant to investigate an element as well as component fixture.debugElement.query(By.css('#shan'))


2 Answers

I'd recommend you use

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

and...

//    Add Item Debug Ele comes out as not null.
addItemDebugElement = componentFixture.debugElement.query(By.css('.addItem'));
expect(addItemDebugElement).toBeTruthy();
like image 85
MGDavies Avatar answered Sep 20 '22 10:09

MGDavies


You can try this to check if the element exist on the Dom

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

or

expect(addItemDebugElement).toBeInDom();
like image 36
Fateh Mohamed Avatar answered Sep 18 '22 10:09

Fateh Mohamed