使用Jasmine捕获传递给不同JavaScript文件中函数的参数

Capture an argument passed to function in different JavaScript file using Jasmine

本文关键字:文件 JavaScript 函数 参数 Jasmine 使用      更新时间:2023-09-26

我有一个JavaScript文件main_one.js,它需要另一个Java脚本文件helper.js

helper.js

warp = {
  postThisEvent: function(a) {
    // some operation on a
  }
};

main_one.js

var Helper = require('path/helper.js');
// some steps
Helper.warp.postThisEvent(event);

我想用Jasmine捕捉event。如何创建用于在postThisEvent()中捕获event的间谍对象?

在Jasmine测试中需要Helper,然后通过以下方式进行侦察:

spyOn(Helper.warp, "postThisEvent").and.callThrough();

这将用间谍函数替换对象Helper.warp上的postThisEvent。当它被调用时,间谍将注册调用,然后按照callThrough()的指示调用原始方法。

然后您可以预期postThisEvent()是通过以下方式使用预期对象调用的:

expect(Helper.warp.postThisEvent).toHaveBeenCalledWith(jasmine.objectContaining({
    someProperty: "someValue"
}));

jasmine.objectContaining()是一个助手,它只测试被测对象的多个属性中是否存在预期属性。

您也可以直接检查复杂的对象:

expect(Helper.warp.postThisEvent.calls.mostRecent().args[0].someProperty).toBe("someValue");

请注意,当postThisEvent()被保存到一个变量中时,这样的间谍可能不起作用,该变量被调用如下:

var postThisEvent = Helper.warp.postThisEvent;
function triggering() {
    postThisEvent({ someProperty: "someValue" })
}
// now a spy is created and then triggering() is called

在这种情况下,在进行间谍活动时无法参考原始方法。在这种情况下,无法在Javascript中拦截函数/方法。

参见

  • Jasmine 2.4间谍和
  • 其他跟踪属性一章中的间谍检查