$.Deferred() and $.ajax() not working in Node.JS

248 views Asked by At

I have the following implementation.

import _ from 'lodash';
import test from 'tape';
import 'jsdom-global/register';
let jQuery = require('jquery')(window);

let $ = global.jQuery = jQuery;

test('check if Deferred work?', (t) => {
  let dfd = $.Deferred();
  let ajax = $.ajax();

  console.log($.extend({}, {a: 1, b:2}), 'dfd', dfd, 'ajax', ajax);
  t.equal(true, true, 'falsey condition');
  t.end();
});

The $.extend works but dfd and ajax not. Any idea how I can make it work?

The error reads: TypeError: $.Deferred is not a function TypeError: $.ajax is not a function

Thanks

EDIT: (possible solution but I'm freaked jsdom library changes so often, IDK if the following will break one day like the deprecated jsdom.env() )

const { JSDOM } = require('jsdom');
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;
import * as jquery from "jquery";
import test from 'tape';
import _ from 'lodash';

test("jquery tests", (t) => {
  t.plan(2);
  const $ = require("jquery")(window);
  $.ajax({url: "http://freegeoip.net/json/"}).done(data => {
    console.log("data is " + JSON.stringify(data));
    t.equal(true, true);
    t.ok(true);
    t.end();
  });
});

output:

$ npx babel-tape-runner ./src/jquery-test.spec.es6.js
TAP version 13
# jquery tests
data is {"ip":"188.90.2xx.4","country_code":"US","country_name":"United States","region_code":"CA","region_name":"California","city":"Orange","zip_code":"92866","time_zone":"America/Los_Angeles","latitude":33.7846,"longitude":-117.8433,"metro_code":803}[object Object]
ok 1 should be equal
ok 2 should be truthy
1

There are 1 answers

2
Rain On

jQuery provide two extend methods. One is static method and another is instance method. You use require('jquery')(window).extend actually use the instance method. But jQuery.Deferred is a static method and cannot be invoked by jQuery instance.

jQuery.extend: Merge the contents of two or more objects together into the first object. jQuery.fn.extend: Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods.