使用 Jasmine 监视没有对象的函数 [英] Using Jasmine to spy on a function without an object

查看:20
本文介绍了使用 Jasmine 监视没有对象的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Jasmine 的新手,刚刚开始使用它.我有一个库 js 文件,其中包含许多与任何对象(即全局)无关的函数.我该如何监视这些功能?

I'm new to Jasmine and have just started using it. I have a library js file with lots of functions which are not associated with any object (i.e. are global). How do I go about spying on these functions?

我尝试使用窗口/文档作为对象,但即使调用了该函数,间谍也不起作用.我还尝试将它包装在一个假对象中,如下所示:

I tried using window/document as the object, but the spy did not work even though the function was called. I also tried wrapping it in a fake object as follows :

var fakeElement = {};
fakeElement.fakeMethod = myFunctionName;
spyOn(fakeElement, "fakeMethod");

并用

expect(fakeElement.fakeMethod).toHaveBeenCalled();

这也不起作用,因为间谍不起作用

This does not work either as the spy did not work

推荐答案

如果你正在定义你的函数:

If you are defining your function:

function test() {};

那么,这相当于:

window.test = function() {}  /* (in the browser) */

所以 spyOn(window, 'test') 应该可以工作.

So spyOn(window, 'test') should work.

如果不是,您还应该能够:

If that is not, you should also be able to:

test = jasmine.createSpy();

如果这些都不起作用,则说明您的设置有其他问题.

If none of those are working, something else is going on with your setup.

我认为您的 fakeElement 技术行不通,因为幕后发生的事情.原来的 globalMethod 仍然指向相同的代码.间谍所做的是代理它,但仅在对象的上下文中.如果你可以让你的测试代码通过 fakeElement 调用它就会工作,但是你就可以放弃全局 fns.

I don't think your fakeElement technique works because of what is going on behind the scenes. The original globalMethod still points to the same code. What spying does is proxy it, but only in the context of an object. If you can get your test code to call through the fakeElement it would work, but then you'd be able to give up global fns.

这篇关于使用 Jasmine 监视没有对象的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆