Reputation: 538
I can get element with using the
fixture.debugElement.query(By.css('h1'));
But what I should to do when I want get element through class name. Something like this
fixture.debugElement.query(By.css('class="name"'))
Upvotes: 47
Views: 114274
Reputation: 606
Sample Test Case based on boolean display text:
it('should set title based on title flag from parent', () => {
component.title ="APP";
fixture.detectChanges();
const title = fixture.debugElement.query(By.css('label')).nativeElement;
expect(title.innerHTML).toContain('APP');
});
fixture.detectChanges() is must if you updated title from .ts file
Upvotes: 1
Reputation: 1198
Make sure By is imported from @angular/platform-browser and not protractor.
Upvotes: 10
Reputation: 261
Just to add some other usefull ways for selecting elements:
// get element with multiple classes
fixture.debugElement.query(By.css('.className1.className2'));
// get a certain element from a group of elements with the same class name
fixture.debugElement.queryAll(By.css('.className'))[1];
Upvotes: 23
Reputation: 209052
You use By.css
to pass a css selector. So any selector you can use with css, you can use with By.css
. And a selector for a class is simply .classname
(with period).
By.css('.classname') // get by class name
By.css('input[type=radio]') // get input by type radio
By.css('.parent .child') // get child who has a parent
These are just some example. If you know css, then you should know how to use selectors.
EDIT:
To use By.css()
be sure to import { By } from '@angular/platform-browser';
Upvotes: 107
Reputation: 137
I would prefer user id on your DOM element and then in angular2 unit test you can call something like below to get reference of your desired DOM element and test what ever you like.
//typscript syntax
fixture = TestBed.createComponent(<your component>);
let result = fixture.nativeElement.querySelector('<id attribute name of html element>');
expect(result.id).toEqual("id of your DOM element.").
Hope this help.
Upvotes: 9