karma-runner / karma-qunit

A Karma plugin. Adapter for QUnit testing framework.
MIT License
51 stars 38 forks source link

qunit 2.x not usable as a module dependency with karma #57

Closed rjatkins closed 2 years ago

rjatkins commented 7 years ago

If the karma.conf.js is set up to run with the frameworks requirejs and qunit, then qunit will register as a amd module, along with binding to the window.QUnit global. With qunit 1.23.1, it's possible to set up requirejs to load this module, as follows:

in test-main.js:

requirejs.config({
    paths: {
        "qunit": "node_modules/qunitjs/qunit/qunit"
    }
});

and in a foo-test.js:

define([
    'qunit'
], function (
    QUnit
) {
    // normal qunit test goes here
});

However, this works only because both context.js (via karma-qunit adapter.js) and require.js are loading qunit.

After upgrading to qunit 2.1.0, the second attempt to load karma via requirejs fails with an error:

  Error: QUnit has already been defined.
  at node_modules/qunitjs/qunit/qunit.js:2001

The standard approach of preventing context.js from loading qunit so that only requirejs loads it then breaks the qunit-adapter. Ideally, the karma-qunit adapter would detect that requirejs was in use, and switch to using requirejs module loading instead.

rjatkins commented 7 years ago

A workaround is to define an additional placeholder for qunit that requirejs can load. As a bonus, this can also export QUnit on its behalf. That is:

in test-main.js:

requirejs.config({
    paths: {
        "qunit": "qunit-define"
    }
});

in qunit-define.js:

define('qunit', [], function() {
    'use strict';

    return QUnit;
});
Krinkle commented 4 years ago

I believe it is not supported for users of Karma to manually load the test framework, unless you also set up the communication layer between the browser and the Karma server. These two go together, and that's what the karma-qunit plugin is for. It loads a copy of QUnit for you, but in a special way that also immediately registers QUnit event listeners for sending results and progress back to the Karma server.

If you are using loading qunit manually for use outside of Karma, e.g. on an HTML test page, I would recommend letting the browser load QUnit directly such as via a script tag.

<script src="node_modules/qunit/qunit/qunit.js"></script>

QUnit has no dependencies so this is generally safe to do anywhere. You can still use RequireJS for everything else.

I hope the above is useful, but I suspect you already considered the above and have to use RequireJS for a specific reason. I will close this issue in a few days, but if you are still experiencing this issue, feel free to comment any time here, I will re-open it. Or simply create a new issue.