【问题标题】:ES2015 import of jQuery not working in test casejQuery 的 ES2015 导入在测试用例中不起作用
【发布时间】:2016-09-15 13:52:19
【问题描述】:

我正在尝试在一个新项目中使用 ES2015 模块,并通过 gulp 使用 Mocha 和 Chai 进行单元测试。我正在将 jQuery 导入源模块(以便它可以调用 getJSON()),但是虽然主要的 $ 函数似乎存在,但附加到它的函数 - 如 getJSONattr - 不.

这是一个最小的测试用例:

// minimal-test-case.js
import $ from "jquery";

export function minimalTestCase1() {
  return $;
}

export function minimalTestCase2() {
  return $.getJSON;
}

下面是它的相应测试:

// minimal-test-case-test.js
import {expect} from "chai";
import {describe, it} from "mocha";
import {minimalTestCase1, minimalTestCase2} from "../../../app/es/services/minimal-test-case.js";

describe("a minimal test case", () => {
  it( "should be able see jquery", () => {
    expect(minimalTestCase1()).to.be.a.function;
  } );

  it( "should be able see jquery functions", () => {
    expect(minimalTestCase2()).to.not.be.undefined;
  } );
});

测试用例 1 成功,但测试用例 2 失败。

对应的gulp任务是:

function testUnitTask() {
  return gulp
    .src(["test/unit/**/*.js"])
    .pipe(gulpMocha({
      compilers:babelCompiler
    }));
}
gulp.task("test:unit", testUnitTask);

import 模式似乎是我在其他地方看到的一种。为什么我看不到$.getJSON

【问题讨论】:

  • 听起来你有冲突。 jQuery 对象是否比 $ 更好?
  • 恐怕jQuery也不起作用。

标签: javascript jquery gulp ecmascript-6


【解决方案1】:

当检测到它位于 commonjs 环境中并且没有可用的全局文档时,您很可能会得到 jQuery 导出的虚拟函数。我建议将 jsdom 添加到您的测试设置中,并添加一个像这样的最小设置文件

const jsdom = require('jsdom').jsdom;
global.document = jsdom('<body></body>');
global.window = document.defaultView;
global.navigator = window.navigator;
global.XMLHttpRequest = window.XMLHttpRequest;

【讨论】:

    【解决方案2】:

    如果你喜欢的话,你可能还想在测试中导入 jquery。

    Something like this
    import $ from 'jquery';
    describe('Prepop test Page', () => {
        beforeEach(() => {
            $('head').append('<meta name="api_token" content="some token" />');
            $('head').append(`<meta name="sample_data" content="${sampleData}"/>`);
            $('head').append('<meta name="action_url" content="/api/ext/v1/prepop/" />');
            $('body').append('<div> </div>');
    

    然后,尽可能模拟您的 jquery 函数和选择器。

    【讨论】:

      猜你喜欢
      • 2016-10-04
      • 1970-01-01
      • 2016-08-22
      • 2012-04-13
      • 2022-01-19
      • 2017-01-09
      • 1970-01-01
      • 2017-12-25
      相关资源
      最近更新 更多