Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/421.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Jasmine(JavaScript)测试委托回调_Javascript_Testing_Jasmine - Fatal编程技术网

使用Jasmine(JavaScript)测试委托回调

使用Jasmine(JavaScript)测试委托回调,javascript,testing,jasmine,Javascript,Testing,Jasmine,我有一个简单的JavaScript函数,它使用两个委托(异步)返回一个值: function getMyUserName() { context.load(user); context.executeQueryAsync(onGetMyUserNameSuccess, onGetMyUserNameFail); } function onGetMyUserNameSuccess() { return user.get_title(); } function onGetMy

我有一个简单的JavaScript函数,它使用两个委托(异步)返回一个值:

function getMyUserName() {
    context.load(user);
    context.executeQueryAsync(onGetMyUserNameSuccess, onGetMyUserNameFail);
}
function onGetMyUserNameSuccess() {
    return user.get_title();
}
function onGetMyUserNameFail(sender, args) {
    return args.get_message();
}
“上下文”和“用户”变量已经设置并初始化,第一个委托(“onGetMyUserNameSuccess”)正在得到正确答案。问题是如何用Jasmine?测试“getMyUserName”函数?。如果我使用“runs”,我无法知道代理的响应(我也看不到任何方法知道代理是否被调用)。我试图设置间谍来嘲笑代表,但可能我没有正确地设置(我只是从Jasmine开始)。 欢迎任何帮助。 提前感谢,,
Gustavo

在大多数情况下,当您必须使用异步代码时,您应该自己调用该函数。但不是直接的,而是代码调用它的方式。因此,在您的示例中,监视
context.executeQueryAsync
并使用
spy.mostRecentCall.args
获取对函数的引用,然后调用它们

var async = jasmin.spyOn(context, 'executeQueryAsync');

async.mostRecentCall.args[0]()

var args = {get_message: jasmine.createSpy()}
async.mostRecentCall.args[1]({}, args);
expect(args.get_message.toHaveBeenCalled());
注意,有一个框架可以自动调用回调