简体   繁体   English

在对Angular JS Promise的notify函数进行单元测试时,永远不会调用notify。

[英]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: 我有一个函数,可以在事情发生时使用notify更新UI:

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? 为什么notify函数不会触发?

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: $ timeout在这里可以解决,因此最终的单元测试代码为:

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();
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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