我是茉莉花的新手,并使用angularjs作为框架。
我如何测试$(window).trigger
“haveBeenCalledWith”:
要测试的代码(它是angularjs服务中的函数):
start: function (serverUrl, callbackFunc) {
// initialize communication manager and when ready start the worklist server
commManager.initAsync(serverUrl, function (isConnected) {
if (isConnected) {
var msgHeader = new protocolMessageHeader(userSessionGuid, messageCommandName.START_WL_SESSION + "_RQ");
var dataSet = { $type: 10, UserSessionGuid: userSessionGuid, WLSessionGuid: wlSessionGuid };
commManager.sendMessage(new protocolMessage(msgHeader, dataSet), function (data) {
if (callbackFunc) {
callbackFunc(data);
}
});
} else {
**$(window).trigger(events.onShowModalDialog, {
title: "Worklist Server Error",
body: "Can not establish connection to Worklist server",
type: generalStatusEnum.ERROR
});**
}
});
}
我将isConnected
设为false,我想测试使用上述参数调用$(window).trigger
答案 0 :(得分:0)
当您的测试代码依赖于其他库/框架时,它总是一个问题。因此,在您的情况下,使用$(window)作为全局事件总线是它使代码难以测试的根。有一些解决方案:
让$()
返回一个模拟,你可以窥探trigger
方法。这将使您的测试代码更加冗长,但您可以保留实际代码:
var trigger = jasmine.createSpy();
spyOn(window, '$').andReturn({trigger: trigger});
yourLib.start('url', callback);
expect(trigger).toHaveBeenCalledWith(events.onShowModalDialog, {
title: "Worklist Server Error",
body: "Can not establish connection to Worklist server",
type: generalStatusEnum.ERROR
});
在你的例子中,你很容易使用$
一次,但是考虑在函数中使用jquery会不会很难或不可能测试函数。
更好的方法是将事件总线传递给您的函数或类的构造函数。例如,您的启动功能可能如下所示:
start: function (serverUrl, callbackFunc, eventBus) {
commManager.initAsync(serverUrl, function (isConnected) {
if (isConnected) {
var msgHeader = new protocolMessageHeader(userSessionGuid, messageCommandName.START_WL_SESSION + "_RQ");
var dataSet = { $type: 10, UserSessionGuid: userSessionGuid, WLSessionGuid: wlSessionGuid };
commManager.sendMessage(new protocolMessage(msgHeader, dataSet), function (data) {
if (callbackFunc) {
callbackFunc(data);
}
});
} else {
eventBus.trigger(events.onShowModalDialog, {
title: "Worklist Server Error",
body: "Can not establish connection to Worklist server",
type: generalStatusEnum.ERROR
});
}
});
}
测试看起来像这样:
var trigger = jasmine.createSpy();
yourLib.start('url', callback, trigger);
expect(trigger).toHaveBeenCalledWith(events.onShowModalDialog, {
title: "Worklist Server Error",
body: "Can not establish connection to Worklist server",
type: generalStatusEnum.ERROR
});
修改强>
只是意识到你的所有代码都包含在回调函数中,所以你也可以监视commManager.initAsync
并调用回调函数:
spyOn(commManager, 'initAsync');
var callback = commManager.initAsync.mostRecentCall.args[1];
callback();