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

查看:125
本文介绍了使用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(窗口,'测试')应该可以工作。

如果是不,你也应该能够:

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天全站免登陆