Angular testing with Jasmine cannot match html node

I am building directory tests in Angular using Jasmine. I have a small test example that looks like this:

it("should compare html node", inject( function ($compile, $rootScope) { var elm = angular.element('<input>'); elm = $compile(elm)($scope); $scope.$digest(); console.log('btn', elm); // output: '<input class="ng-scope">' expect(elm).toBe('<input class="ng-scope">'); expect(elm[0]).toBe('<input class="ng-scope">'); // these also fail expect(elm.html()).toBe('<input class="ng-scope">'); // "" })); 

So, I get the expected output to the console, but Jasmine complains about the error Expected { length: 1, 0: HTMLNode } to be '<input class="ng-scope">'

I also tried using elm[0] , which gives the same error and elm.html() , but that just returns an empty string. How can I compare HTML Node with string correctly?

NB I know this is an unrealistic test, but I just want to demonstrate my current problem.

+7
angularjs angularjs-directive jasmine
source share
2 answers

So elm is angular.element , which is a jqLite object. As you point out, you can use elm [0] to get the actual dom element. Then you can access the html node by accessing the .outerHTML field. Therefore, our final decision is to use

 elm[0].outerHTML 
+10
source share

When running Jasmine tests, I tested element.html() to then use jQuery to search for specific conditions like

 expect(element.html()).toContain($('input.ng-scope')); 

I went deeper and tried to see a comparison of HTMLNode with HTMLNode, but I think this is a limitation of Jasmine. You can try,

 expect(element[0]).toEqual($.parseHTML('<input class="ng-scope">')[0]) 

But Jasmine returns "Expected HTMLNode to match HTMLNode." The best way is best to deconstruct the compiled HTML element, as shown above, with various test cases.

0
source share

All Articles