2016-12-02 35 views
0

當我們有興農:測試函數調用和無功變化的順序

// arrange 
var testVar = 0; 
var testFunction = sandbox.stub(); 

// act 
TestClass.TestMethod(); // it changes testVar and calls testFunction 

有沒有一種方法,如果testFunction調用之前的testvar改變測試?

編輯:看起來好像沒有。但!如果變量是對象屬性,則可以執行類似的操作。在下面檢查我自己的答案。

+1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch – mplungjan

+0

良好之一,但它的壁虎只,和我在這裏做單元測試:)我可以通過使用代理儘管我的方式... –

+1

Sinon和代理都不能用來檢測標量變量是否改變。 – robertklep

回答

0

好吧,看起來它不能真正做到。

但是,我確實找到了一種方法來測試對象屬性。例如僞代碼:

before(function() { 
    var functionCallOrder = []; 

    document.body.classList.add = function() { 
     functionCallOrder.push('added class'); 
    }; 

    Object.defineProperty(document.body, 'scrollTop', { 
     set: function() { 
      functionCallOrder.push('changed viewport location'); 
     } 
    }); 

    it('should set a class before changing the viewport location'), function() { 
      // act 
      MyModule.methodThatDoesWhatTheDescriptionSays(); 

      // assert 
      expect(functionCallOrder).to.deep.equal([ 
       'added class', 
       'changed viewport location' 
      ]); 
    }); 
});