6

$timeout が呼び出されていないことを確認できるように、$timeout をスパイしようとしています。具体的には、私の製品コード (以下を参照) は $timeout をオブジェクトではなく関数として呼び出します。

$timeout(function() { ... })

ではない

$timeout.cancel() // for instance

ただし、Jasmine では、次のようにスパイ対象のオブジェクトが必要です。

spyOn(someObject, '$timeout')

ただし、「someObject」が何であるかはわかりません。

違いがある場合は、Angular モックを使用しています。

編集: テストしようとしている関連する製品コードは次のようになります。

EventHandler.prototype._updateDurationInOneSecondOn = function (call) {
    var _this = this;
    var _updateDurationPromise = this._$timeout(function () {
            call.duration = new Date().getTime() - call.startTime;
            _this._updateDurationInOneSecondOn(call);
        }, 1000);
    // ... more irrelevant code
}

特定のテスト シナリオでは、$timeout が呼び出されなかったことを主張しようとしています。

編集 2: $timeout をオブジェクトではなく関数として使用していることを明確に指定しました。

4

3 に答える 3

1

angular$timeoutは、関数を実行/呼び出すサービスです。「スパイ」への要求$timeoutは、Y の指定された時間に X の機能を実行している場合に少し奇妙です。このサービスをスパイするために私がすることは、タイムアウト関数を「モック」し、コントローラーに次のように挿入することです。

 it('shouldvalidate time',inject(function($window, $timeout){

        function timeout(fn, delay, invokeApply) {
            console.log('spy timeout invocation here');
            $window.setTimeout(fn,delay);
        }

//instead of injecting $timeout in the controller you can inject the mock version timeout
        createController(timeout);

// inside your controller|service|directive everything stays the same 
/*      $timeout(function(){
           console.log('hello world');
            x = true;
        },100); */
        var x = false; //some variable or action to wait for

        waitsFor(function(){
            return x;
        },"timeout",200);

...
于 2014-01-19T23:02:57.923 に答える
0

このコードは私のために働く

var element, scope, rootScope, mock = {
    timeout : function(callback, lapse){
        setTimeout(callback, lapse);
    }
};

beforeEach(module(function($provide) {
    $provide.decorator('$timeout', function($delegate) {
      return function(callback, lapse){
          mock.timeout(callback, lapse);
          return $delegate.apply(this, arguments);
      };
    });
}));
describe("when showing alert message", function(){

    it("should be able to show message", function(){
        rootScope.modalHtml = undefined;
        spyOn(mock, 'timeout').and.callFake(function(callback){
            callback();
        });
        rootScope.showMessage('SAMPLE');

        expect(rootScope.modalHtml).toBe('SAMPLE');

    });

});
于 2014-12-28T16:27:50.127 に答える