2

我有以下实现。

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();
});

$.extend 有效,但dfd无效ajax。知道如何使它工作吗?

错误显示:TypeError: $.Deferred is not a function TypeError: $.ajax is not a function

谢谢

编辑:(可能的解决方案,但我很害怕 jsdom 库更改如此频繁,IDK 如果以下内容有一天会像弃用的那样中断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();
  });
});

输出

$ 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
4

1 回答 1

0

jQuery 提供了两种扩展方法。一种是静态方法,另一种是实例方法。您使用 require('jquery')(window).extend 实际上使用实例方法。但是 jQuery.Deferred 是一个静态方法,不能被 jQuery 实例调用。

jQuery.extend:将两个或多个对象的内容合并到第一个对象中。jQuery.fn.extend:将对象的内容合并到 jQuery 原型上,以提供新的 jQuery 实例方法。

于 2017-09-07T06:11:08.363 回答