0

I am using controller to change the class of an object in angularjs

$scope.$watch('sideQuery',function(){
        if($scope.sideQuery==""){
            $(".indicator").removeClass('glyphicon-minus');
            $(".indicator").addClass('glyphicon-plus');

        }
        else{
            $(".indicator").removeClass('glyphicon-plus');
            $(".indicator").addClass('glyphicon-minus');

        }
    });

How to test using karma? a function like

expect(scope.elem('.indicator').hasClass("glyphicon-plus")).toBe(true);

2 Answers 2

4

Please, do not use jQuery to toggle classes in Angular, it defeats the purpose of it. Use ng-class and apply your classes based on flags, like so:

<div class="indicator" ng-class="{'glyphicon-minus' : sideQuery != '', 'glyphicon-plus':sideQuery == ''} ></div>

Then in testing check the value of sideQuery and know that you'll have classes based off that.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! :-) How to test whether the element has that class('glyphicon-plus') or not?
Dont test the element, test that scope variable, if it's empty, it has that class plus - else minus
3

If you are testing a directive, then you can compile a sample element and test the result object.

var $element;
beforeEach(inject(function ($compile) {
    $element = $compile('<div data-my-directive></div>')($scope);
}));

it('should have the class "someClass"', function(){
    expect($element.hasClass('someClass')).toBe(true);
});

However, be aware that tymeJV is right, you should use the ng-class directive and test your scope's values. If the scope value is right, then the class will be applied (you don't have to test the ng-class directive, that's something done in Angular's unit tests).

5 Comments

I am testing in controller and it is showing ReferenceError: $compile is not defined
You will need to inject the $compile service in
@Stranger, you shouldn't use jQuery in a controller, that's something that should be done in a directive. As for the $compile variable, it must be injected in the function where you are going to use it (I've just updated the code).
sorry for irritating you. It is showing.... beforeEach(inject(function ($compile) { $element = $compile('<div data-my-directive></div>')(scope); })); TypeError: undefined is not a function at null.<anonymous> TypeError: scope.$element is not a function
@Stranger, no problem, it's kinda difficult to write code here in comments, take a look at this example of a directive's unit testing. scope.$element doesn't exist... $element is a variable defined inside your test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.