2016-03-10 101 views
0

我需要驗證在EmberJS中使用摩卡單元測試調用jqxgrid的'rowClicked'動作。我有一個網格初始化,並可以驗證它得到渲染,行和標題呈現,但我堅持在rowclick事件。我使用jQuery模擬點擊上這樣一行:單元測試jqgrid動作

this.$('#row0grid_testgrid').trigger('click'); 

我的網格代碼偵聽rowClick事件是這樣的:

this.grid().on('rowclick', function(evt) { 
     // My code here 
    }); 

我如何驗證這個被調用? 謝謝

回答

0

你可以做這樣的事情 - 嘲笑功能?

/*** in your unit test ***/ 
//... get your grid object ... 
const gridComponent = .... 

// save the original function to assign it later back 
const originalOn = gridComponent.on; 

// now mock the on function 
gridComponent.on = function(actionName, handler){ 
assert.ok(true, "on() function has been called"); 

assert.equal(actionName, "rowclick", "the action on which on() function has been triggered is correct"); 
} 

// execute tested context 
this.$('#row0grid_testgrid').trigger('click'); 

// tidy up 
gridComponent.on = originalOn; 

有幾件事情需要在這裏提一下:如果這個工程,你將測試on()已經調用了它被觸發正確的動作「rowclick」。但是,您仍然無法測試代碼「// My code here」中的部分內部函數。

如果你想測試你的函數,你可以做的是從它調用匿名函數。讓我告訴你我是什麼意思:

/*** your component code ***/ 
// this will be called on "rowclick" 
myComponentFunction: function(whatArgument){ 
    // My code here 
} 

.... 
const self = this; 
this.grid().on('rowclick', function(evt) { 
     // instead of pure code call a function 
     const someParameters = "foo"; 
     self.myComponentFunction(someParameters);  
}); 
... 

在你的單元測試,你就能夠也myComponentFunction嘲笑:

// same unit test 
.... 
const originalMyComponentFunction = gridComponent.myComponentFunction; 

gridComponent.myComponentFunction = function(arg){ 
assert.ok(true, "myComponentFunction() has been called!"); 

// test argument, whatever 
assert.equal(arg, "foo", "argument passed to myComponentFunction() from an event triggered on 'rowclick' is correct"); 
} 

// tidy up myComponentFunction mock, too. 
gridComponent.myComponentFunction = originalMyComponentFunction; 

順便說一句,首選方式設立嘲笑和整理起來是把它變成beforeEach()和afterEach(),看看ember-cli testing guides

如果你有什麼更好的想法如何測試這個,我想向你學習:)

+0

謝謝!模擬工作得很好。我不需要測試函數本身,但如果需要,我會保持這種想法。 – Lazloman