2

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
Pristine Kallio
  • 505
  • 5
  • 19
  • Try dropping the `(window)` after requiring jQuery. I don't think you need that, and it would explain the error - your `jQuery` is actually an instance. Can you `console.log($)` and `console.log(Object.keys($))`? – Bergi Sep 07 '17 at 06:25

1 Answers1

0

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.

Rain
  • 1
  • 1
  • I tried this: `import _ from 'lodash'; import test from 'tape'; import 'jsdom-global/register'; import $ from 'jquery'; console.log('AJAX', $.ajax(), 'DEFERRED', $.Deferred());` with a simple test case and cannot get them to work, Error: Error: Invalid protocol: about: – Pristine Kallio Sep 07 '17 at 06:39
  • so... any solutions for this case? – gumuruh Aug 19 '20 at 03:12