Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using element.find() by class in Angular Unit testing

When running this test, I keep getting the error Expected undefined to be true.

it('should have the right classes', function() {
   // this doesnt work
   expect(element.find('.exampleClass').hasClass('ng-hide')).toBe(true);

   // but this works
   expect(element.find('span').hasClass('ng-hide')).toBe(true);
});

How can I use jqlite to find an element by id and class?

like image 837
cusejuice Avatar asked Jul 07 '15 02:07

cusejuice


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.

What is debugElement in Angular?

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

What is Jasmine debugElement?

debugElement is a Angular's method. . nativeElement() is Browser specific API that returns or give access to DOM tree. But what if application is running on non-browser platform (such as server or web-worker), in that case .

What is TestBed in Angular testing?

TestBed is the primary api for writing unit tests for Angular applications and libraries. Note: Use TestBed in tests. It will be set to either TestBedViewEngine or TestBedRender3 according to the compiler used.


1 Answers

That is because angular-jqlite (very lightweight library when compared to jquery itself) find is limited to look up by tag names only. You can use element.querySelector(All) and wrap it in angular.element. i.e

  var elm = element[0];
  expect(angular.element(elm.querySelector('.exampleClass')).hasClass('ng-hide')).toBe(true);

  //Or even
  expect(elm.querySelector('.exampleClass.ng-hide')).toBeDefined();

See documentation

find() - Limited to lookups by tag name

like image 68
PSL Avatar answered Sep 22 '22 05:09

PSL