Tips for importing modules for unit tests using QUnit

Lately, I've been working on implementing unit tests for some of my modular ES6 code. The project structure I have looks something like this:

project
└───src
|   └───js
|           cumsum.js
|       index.js <--- main file
└───test
        tests.js <--- QUnit testing code

Inside the cumsum.js file, you'll find the following function:

export const cumsum=x=>{
    var result = x.reduce((r, a)=> {
        if (r.length > 0) {
            a += r[r.length - 1];
        }
        r.push(a);
        return r;
    }, []);
    return result;
}

When I run a basic test using qunit in the terminal, it works perfectly fine:

const A=[1,2,3,4,5];
const expected=[1,3,6,10,15];
QUnit.test( "cumsum", function( assert ) {
    assert.deepEqual([1,3,6,10,15],expected);
});

However, the issue arises when I try to import the actual cumsum function using ES6 import syntax:

import {cumsum} from '../src/js/cumsum';
const A=[1,2,3,4,5];
const expected=[1,3,6,10,15];
QUnit.test( "cumsum", function( assert ) {
    assert.deepEqual(cumsum(A),expected);
});

When attempting this, an error message appears stating

SyntaxError: Unexpected token {

Is there a way to effectively use QUnit with ES6 modules? If not, are there alternative unit testing frameworks that support testing these modules?

Answer №1

Here's the progress I've made so far.

Chrome has some limited capability to run ES6 modules natively. While it may not be suitable for web production, it can be used for running certain unit tests. In the test directory, I've set up the index.html file like this:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>QUnit Example</title>
  <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.9.2.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="https://code.jquery.com/qunit/qunit-2.9.2.js"></script>
  <script type="module" src="../src/js/cumsum.js"></script>
  <script type="module" src="tests.js"></script>
</body>
</html>

In the test/tests.js file, I have the initial test code:

import {cumsum} from '../src/js/cumsum';
const A=[1,2,3,4,5];
const expected=[1,3,6,10,15];
QUnit.test( "cumsum", function( assert ) {
    assert.deepEqual(cumsum(A),expected);
});

However, it's worth noting that you can't directly open the test/index.html file in the web browser. This is because Chrome struggles when the type="module" attribute is set for local files. Instead, you need to run a web server and access it that way. Any development server will suffice, such as webpack-dev-server. Simply open http://localhost:8080/test/ in Chrome, and the unit tests will be displayed.

Is there a more efficient way to accomplish this task? Considering that Node.js utilizes the same JavaScript engine as Chrome, it might be feasible to achieve this through the command line without the need for a web server and browser.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The perplexing configuration of a webpack/ES6 project

I am currently in the process of setting up my very first ES6 and webpack "application" where I aim to utilize classes and modules. However, each time I attempt to transpile the application using the webpack command, I encounter the following error: $ web ...

Using JavaScript, extract current date from an API data

Here is an example of how the data from my API appears: const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "i ...

Retrieving text data from the JSON response received from the Aeris API

I am attempting to showcase the word "General" text on the HTML page using data from the API found under details.risk.type. The JSON Response Is As Follows... { "success": true, "error": null, "response": [ ...

Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with: let time = 0 let activated = 0 function changePic() { if(a ...

Although my ajax request was unsuccessful, I was able to successfully upload my post

Why is my ajax request failing while still uploading my post? How can I prevent this failure? Here is my ajax request code: createRate(){ var ourNewPost = { 'title': $(".new-rate-title").val(), 'content': $('. ...

Effortlessly glide to a specific div ID upon page load using the URL address

One way to implement smooth scrolling to an anchor on page load is by using jQuery. Here's an example code snippet: $(function(){ $('html, body').animate({ scrollTop: $( $('#anchor1').attr('href') ).offset(). ...

Unable to bind knockout dropdownlist data during an ajax request

Trying to connect a dropdownlist in knockout with MVC 4. Below is the code snippet: Action public JsonResult GetUserTypes() { using (QuestApplicationEntities db = new QuestApplicationEntities()) { var usertypes = (from ...

Unable to retrieve value - angularJS

An AngularJS application has been developed to dynamically display specific values in an HTML table. The table consists of six columns, where three (Work Name, Team Name, Place Name) are fixed statically, and the remaining three columns (Service One, Servi ...

Strange behavior of shadows within Three.js

I've been working on creating a mini solar system but encountered an interesting issue. I want all the planets to cast and receive shadows from each other, but it seems like the shadow casting depends on the order of instancing. Here is the code for t ...

Ajax implementation for handling URL action parameters

I am currently facing challenges in passing data from a view to a controller using parameters. My goal is to pass these parameters when I select a row from a table and click on a button that triggers the ShowTasks() function. Here is the C# controller cod ...

Ways to shift pictures sequentially in a horizontal line?

I am currently working on a project in asp.net where I need to rearrange 'x' number of images in a row. To explain the scenario, let's say we have 5 images labeled as 1, 2, 3, 4, and 5. Initially, they are in the order of 1, 2, 3, 4, 5. Then ...

execute web browser function using Node.js

Is it possible to use http to remotely send a request and retrieve data from a specific site, such as google.com? I'm curious about how to utilize node for browser actions, like navigating to google.com, interacting with the input bar, and triggering ...

Update the month in the second date picker to align with the selection made in the first date picker within the Angular framework

Is it possible to dynamically change the month of the second datepicker based on the selection made in the first date picker? Currently, it is displaying the current date by default. For example: If I select 15-10-2104 from the first date picker, the secon ...

What is the process for converting this code to HTML format?

I am new to programming and I am using an API with node.js to display the result in a browser. The API is working fine with console.log, but I want to render it on the browser instead. I am using Jade template for this purpose. How can I write the code t ...

Oops! It seems like there was an issue trying to access properties that are undefined while reading 'pipe' in Angular12

I encountered an issue when trying to send an AJAX request, displaying the following error message: ERROR TypeError: Cannot read properties of undefined (reading 'pipe') This error occurred in the ajax-loader.interceptor.ts class export class A ...

The search functionality for the MongoDB module is not functioning properly within my Next.js application

Working on my nextjs application, I have encountered an issue with using the mongodb node module to find all documents in one of my collections. Despite successful usage of .findOne and .updateOne for other pages like login and password reset, when I use . ...

Show input field depending on chosen option

I'm looking to create a dynamic form where specific input fields are displayed based on the selection made in another field. For example, if "gender: male" is selected, the input field for "blue" should appear, and if "gender: female" is selected, the ...

Angular: Enhancing URL links

Recently, I discovered a function in my code that allows me to cycle through different pictures and change the URL accordingly. The initial URL is obtained using angular routes, where the "domain" parameter consists of the domain.id and the domain.category ...

Combine Two Arrays into a JSON Object and Merge Duplicate Key Values without Using ES6 in JavaScript

Seeking a swift javascript solution to merge two arrays with the same length into an array of json objects. In addition, the code should append any errors to the existing .error element. Preferably, the solution should utilize vanilla javascript instead of ...

Is there a way to stop the page from scrolling once I reach the bottom of a specific div within it?

My webpage has multiple divs that share a similar structure: <div style="height:200px; overflow:auto;"> <div style="height:300px;"> <!--There is a lot of content here--> </div> </div> When the user hovers ove ...