Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Angular 2 element through class name in Jasmine

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"')) 
like image 768
user2510058 Avatar asked Oct 17 '16 10:10

user2510058


People also ask

What is the purpose of Angular's by class?

Angular defines a number of decorators that attach specific kinds of metadata to classes, so that the system knows what those classes mean and how they should work.

How does Jasmine define Angular spec?

We use the Jasmine-provided it function to define a spec. The first parameter of it is a text description of what the spec will be testing — in this case we have a defined component. The second parameter is a function that will run the test. We then use Jasmine's expect function to define our expectation.

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

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';

like image 94
Paul Samsotha Avatar answered Sep 19 '22 20:09

Paul Samsotha


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]; 
like image 26
Duarte Avatar answered Sep 23 '22 20:09

Duarte