简体   繁体   中英

When unit testing an Angular JS Promise's notify function, notify is never called

I have a function that uses notify to update the UI when things are happening:

promiseFunction.poll().then(
   function resolve() {},
   function reject() {},
   function notify() {
       console.log('Notify was called');
   }
);

And a unit test trying to mock the notify

it('will call notify', function () {
    sinon.stub(promiseFunction, 'poll', function () {
        var pollDeferred = $q.defer();
        pollDeferred.notify();
        return pollDeferred.promise;
    });

    systemUnderTest.run();
    $rootScope.$digest();

});

The log 'Notify was called' never gets logged. Why won't the notify function fire?

Ok so I resolved this in the end. It makes sense when thinking about it. Notify isn't resolving and therefore fulfilling the promise, so it cannot be sent before the promise has been returned to the caller. $timeout came to the rescue here, so the end resulting unit test code is:

it('will call notify', inject(function ($timeout) {
    sinon.stub(promiseFunction, 'poll', function () {
        var pollDeferred = $q.defer();

        $timeout(function () {
            pollDeferred.notify();
        }, 0);

        return pollDeferred.promise;
    });

    systemUnderTest.run();
    $timeout.flush();
    $rootScope.$digest();
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM