简体   繁体   English

Jasmine-node - 在其他函数内部调用的构造函数上创建一个间谍

[英]Jasmine-node - Creating a spy on a constructor called inside other function

I'm novice in jasmine and I need to write some unit tests for node.js app in this framework. 我是茉莉花的新手,我需要在这个框架中为node.js应用程序编写一些单元测试。 I have some problems, one of them is this described below: 我有一些问题,其中一个问题如下所述:

var sampleFunction = function(){
    var loader = new Loader(params);
    // rest of logic here
}

I want to write unit test for sampleFunction . 我想为sampleFunction编写单元测试。 To do this I need to create spy on Loader constructor and check what this constructor gets as params and what kind of object is it returning. 为此,我需要在Loader构造函数上创建spy,并检查这个构造函数作为params获取的内容以及它返回的是什么类型的对象。

Any ideas how to do that? 任何想法如何做到这一点? I tried to create spy on Loader.prototype.constructor but it wasn't a solution to this problem. 我试图在Loader.prototype.constructor上创建间谍,但它不是这个问题的解决方案。

OK, so normally in client-side JavaScript you would use the window object like so jasmine.spyOn(window, 'Loader') 好吧,通常在客户端JavaScript中你会使用像jasmine.spyOn(window, 'Loader')这样的窗口对象jasmine.spyOn(window, 'Loader')

In node, however, there is no window object and despite claims to the contrary global is not a substitute (unless you are in the REPL which runs in global scope). 但是,在节点中,没有窗口对象,尽管声称相反,全局不是替代(除非您在全局范围内运行的REPL中)。

function MyConstructor () {}
console.log(global.MyConstructor); --> undefined
console.log(this.MyConstructor); --> undefined

So, in node you need to attach your constructor to an object. 因此,在节点中,您需要将构造函数附加到对象。 So just do something like this 所以只做这样的事情

var Helpers = {
   Loader: Loader
};

var constSpy = jasmine.spyOn(Helpers, 'Loader').andCallThrough();

sampleFunction();

expect(constSpy).toHaveBeenCalled();

The andCallThrough call is only necessary if you want your constructor to do something (often with constructor you do). 只有在你希望构造函数做某事时(通常使用构造函数),才需要调用andCallThrough

This is a little hacky, but it works and seems to be the only way to achieve this through jasmine's implementation within node. 这有点hacky,但它的工作原理似乎是通过jasmine在节点内实现来实现这一目标的唯一方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM