0

I need to test some code in Angular with Jasmine, but the thing is that I can't do this because of $timeout call. So the code looks like this:

$scope.add = function() {
    SomeService.add(id, function() {
        $timeout(function() {
            $scope.showSuccessMessage();
        }, 1000)
    }, function() {})
};

So the test code is:

describe('method add', function() {
    it('should add', function() {
        spyOn(SomeService, 'add').and.callFake(function(id, successCallback, errorCallback) {
            spyOn(scope, 'showSuccessMessage');
            successCallback();
            expect(scope.showSuccessMessage).toHaveBeenCalled();
        });
        scope.add();
        expect(SomeService.add).toHaveBeenCalled();
    });
});

And the problem is that because of the timeout call I can't check that showSuccessMessage() has been called. I know about Jasmine's ability to work with timeouts but in that case I can't find a working way because of calling it in the callback.

1
  • you could put expect under setTimeout, it works for me :) Commented Dec 17, 2017 at 8:23

2 Answers 2

2

You can flush your timeout by using $timeout.flush() after calling the original function. That should allow you to access the successCallback.

Also, I would put the spy and expect of the showSuccessMessage outside the other spy

describe('method add', function() {
    it('should add', function() {
        spyOn(SomeService, 'add').and.callFake(function(id, successCallback, errorCallback) {
            successCallback();
        });
        spyOn(scope, 'showSuccessMessage');
        scope.add();
        $timeout.flush();
        expect(SomeService.add).toHaveBeenCalled();
        expect(scope.showSuccessMessage).toHaveBeenCalled();
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

Im not very familiar with the workings of angular, I hope this helps:

You can use the done function for asynchronous code:



    it('should add', function (done) {
        $scope.successCallback = function () {
            // successCallback was called
            done();
        }

        $scope.add();
    });


1 Comment

AngularJS ngMock module was designed to provide synchronous tests in Jasmine. done is never needed for testing purely Angular code.

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.