Using QUnit CLI - Having issues with import / export syntax

148 Views Asked by At

I think the issue is with differences using ES Modules vs Common JS Module vs Webpack, but I have come here to actually find out what's wrong!

Basically I have QUnit set up and running fine through the browser. But I want to add it to our dev command line testing process so that QUnit is ran too. I found QUnit CLI and it was easy to get up and running.

I run my test file with npx qunit path/to/test/*.js

//Working test example running from cli.
QUnit.module('math');
function add(a, b) {
    return a + b;
}
QUnit.test('add two numbers', assert => {
    assert.equal(add(1, 2), 3);
});

But when I want to actually test real code from files in our project I get errors such as - SyntaxError: Cannot use import statement outside a module so I tried changing the file to .mjs which then fails with import { Code } from '../code/Code.js'; ^^^^^^ SyntaxError: Named export 'Code' not found. The requested module '../code/Code.js' is a CommonJS module, which may not support all module.exports as named exports.

Ideally I would like my testing environment to go through a similar path as actually visiting the main website.

Another issue I am assuming is because of webpack.

In webpack we have:

        resolve: {
            alias: {
                '@': path.resolve( __dirname, 'code/files' )
            },
        },

Which then all our files for example are imported with import { CodeThing } from '@/somecode/CodeThing';. Is there anyway to make webpack and QUnit work together in a friendly way?

Example Full Test Code I want QUnit to run:

import { CodeThing } from '@/somecode/CodeThing.js';
QUnit.module( 'CodeThing' );
QUnit.test( 'CodeThing.Round', function( assert ) {
    assert.ok( CodeThing.Round( 1.005, 2 ) === 1.01, 'CodeThing.Round(1.005, 2) === 1.01 -- Passed!' );
} ) ;

Then CodeThing.js contains code like:

import { MoreCode } from '@/code/MoreCode';
import { OtherCode} from '@/code/OtherCode';

export var CodeThing = function() {
};


CodeThing.Round = function( int, decimal_places ) {
//Code
};

CodeThing.FuncTwo = function( param ) {
//Code
};
0

There are 0 best solutions below