你可以做這樣的事情 - 嘲笑功能?
/*** 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。
如果你有什麼更好的想法如何測試這個,我想向你學習:)
謝謝!模擬工作得很好。我不需要測試函數本身,但如果需要,我會保持這種想法。 – Lazloman