在节点环境(jQuery 2.x)中存根jQuery.ajax [英] Stubbing jQuery.ajax in node environment (jQuery 2.x)

查看:70
本文介绍了在节点环境(jQuery 2.x)中存根jQuery.ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行一些需要对jQuery.ajax进行存根的测试.我正在使用SinonJS来做到这一点,它过去可以与旧版jQuery(1.x)正常工作

I am trying to run some tests that require stubbing jQuery.ajax. I'm using SinonJS to do that and it used to work fine with older version of jQuery (1.x)

var $ = require('jquery');
var sinon = require("sinon");
sinon.stub($, "ajax"); // this worked because $.ajax is defined

但是,升级到jQuery 2.x之后,当我需要模块中的jquery来运行它时,我不得不包含一个窗口环境.我正在使用jsdom完成此操作:

However, after upgrading to jQuery 2.x, I have had to include a window environment when I require jquery from my module for it to run. I am using jsdom to accomplish this:

var document = require('jsdom').jsdom(),
    window  = document.parentWindow,
    $       = require('jquery')(window);

问题 $.ajax现在未定义.我怀疑,因为现在它返回绑定到特定元素的jQuery对象,但并不完全确定.有谁知道为什么以及如何解决这个问题?

PROBLEM $.ajax is now undefined. I suspect because now it returns the jQuery object bound to a specific element but not entirely sure. Does anyone know why and how to get around this?

编辑我的一个不在SO上的伙伴指出,如果将window附加到global,则可以获取普通的jquery对象而不是工厂

EDIT A buddy of mine who isn't on SO has pointed out that if we attach window to global, we can get the plain jquery object instead of the factory

    global.window = require('jsdom').jsdom().parentWindow;
    var $ = require('jquery'); // this works as $.ajax is now defined

我不喜欢将window附加到global,因为它会影响某些类型为check window的插件.不是障碍,但我很想看看是否还有其他方法可以解决此问题.

I'm not a fan of attaching window to global as it will affect up some of the plugins which type check window. Not a blocker, but I'd love to see if there is any other way to go around this problem.

推荐答案

在宣读了jquery的源代码之后,我本可以发誓,我在问问题的那一天尝试了此操作,但没有成功.我刚刚再次尝试过,并且可以正常工作.

I could have sworn that after reading jquery source, I tried this on the day I asked the question but it didn't work. I tried again just now and it's working.

tl; dr jQuery jQuery将$附加到浏览器模拟器的窗口名称空间.

tl;dr jQuery attaches $ to the window namespace for browser emulator.

var document    = require('jsdom').jsdom(),
    window      = document.parentWindow;
require('jquery')(window);
var $ = window.$;

希望对其他人有用.

这篇关于在节点环境(jQuery 2.x)中存根jQuery.ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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