Easy steps for creating unit tests in a project that utilizes RequireJS

I've been attempting to write unit tests using chai mocha, but I keep encountering the error below.

ReferenceError: define is not defined

The application I'm working on is written in TypeScript. Interestingly, when I create a dummy file for testing purposes without any imports, it runs smoothly.

Below is the code for the unit test:

import { expect } from 'chai';
import { MarionetteApp } from '../app/app';

describe("MarionetteApp", () => {
    describe("Add", () => {
        it("Should return 3 when a = 1 and b = 2", () => {
            let calc = new MarionetteApp();

            var result = calc.test();

            expect(result).to.equal("hello");
        });
    });
});

The specific file I intend to test is as follows:

import { RootView } from './views/RootView';
import { AdvancedCustomController } from './controllers/AdvancedCustomController';
import * as DB from './db/DB';


export class MarionetteApp extends Marionette.Application {

    constructor() {
        super();
    }

    test(){
        return "hello";
    }

    initialize() {
        (<any>window).UXToolApp = this;
    }

    onBeforeStart() {
        //Init controllers
        var advancedCustomizationController = new AdvancedCustomController();

        //Init views
        var rootView = new RootView();
        rootView.render();
    }

}

However, when running the unit test, I encounter the following error message:

Here's the tsconfig file configuration:

 "version": "1.5.0-beta",
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
        // "module": "commonjs",
        "isolatedModules": true,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": true,
        "noImplicitAny": false,
        "removeComments": false,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true,
        "rootDir": "./app",
        "moduleResolution" : "node"
    },

Lastly, the package.json configuration:

{
  "name": "design_mode",
  "version": "1.0.0",
  "description": "",
  "main": "scripts/designMode.ts",
  "directories": {
    "test": "test"
  },
  "dependencies": {
    "amd-loader": "^0.0.8",
    "amdefine": "^1.0.1",
    "chai": "^4.1.2",
    "mocha": "^5.0.3",
    "requirejs": "^2.3.5",
    "ts-node": "^5.0.1",
    "ws": "^0.4.32"
  },
  "devDependencies": {
    "del": "^2.0.0",
    "gulp": "^3.9.0",
    "gulp-less": "^3.0.3",
    "gulp-rename": "^1.2.2",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-tslint": "^3.2.0",
    "gulp-typescript": "^2.8.1",
    "gulp-util": "^3.0.6",
    "less": "^2.5.1",
    "tsd": "^0.6.4",
    "typescript": "^2.7.2"
  },
  "scripts": {
    "test": "./node_modules/.bin/mocha --compilers ts:ts-node/register ./test/*.spec.ts",
    "server": "cd server && node server.js",
    "build": "gulp"
  },
  "author": "",
  "license": "ISC"
}

Answer №1

To fix the problem, navigate to the main project folder and install the amd-loader module. After that, execute the command provided below.

node node_modules/mocha/bin/mocha --require ts-node/register -r amd-loader --timeout=0 tests/**/*.ts

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

"Encountering an error searching for the chai module in the node modules folder even though

Attempting to install chai through the command line, I used the following command. npm install --save-dev chai After that, I attempted to run my unit test class with the specified imports: import {assert} from 'chai'; import {expect} from &ap ...

Creating a TypeScript function that can dynamically assign values to a range of cells within a column, such as AD1, AD2, AD3, and so on

Hello there I'm currently working on a function that will dynamically assign values to the column range of AE to "AD" + i. However, when I use the function provided below, it only writes AD5 into the first 5 columns instead of AD1, AD2, AD3, and so o ...

When attempting to build the iOS app with Ionic, the error "Unable to access property toLowerCase of undefined" is

When attempting to build ios in Ionic3 using the command: ionic cordova build ios, I encounter the error "Cannot read property toLowerCase of undefined". Below is the log output with the --verbose flag: > ionic-app-scripts build --target cordova --pla ...

Store a value in a data container

I am completely new to working with node.js and while I have a basic understanding of its functionality, I believe there is something crucial that I am missing when it comes to how fs.write and buffers work. My goal is to send a user-defined variable over ...

How to assign the value of one property to another property within an object using AngularJS

Is this a silly question? $scope.registration = { email: "", userName: "", password: "", confirmPassword: "", firstName: "DummyFirstName", lastName: "DummyLastName" }; I want to set the userName to be t ...

The PHP counter conceals the comma upon loading and does not display it permanently

I'm currently working on a PHP counter and encountering an issue with the comma display. I have implemented Number Format in a PHP function to print counter digits with commas every 3 digits, but the comma doesn't remain visible after the page lo ...

Encountering trouble with Angular material library following upgrade to Angular 6

Upon attempting to compile the application, I encountered the following error: ERROR in src/app/app.module.ts(15,5): error TS2304: Cannot find name 'MatToolbarModule'. src/app/app.module.ts(16,5): error TS2304: Cannot find name 'MatSidenavM ...

Is web analytics done via client-side (JavaScript) or server-side logging on websites?

As I embark on creating a web application to track web statistics for my clients, I've run into a dilemma. With the rise of ajax usage, I'm unsure whether it's best to log a user visit using JavaScript or serverside. Additionally, I'm u ...

Issue with Vue Router failing to navigate to the correct hash location

After clicking a link on the app, I noticed that the Router does scroll to the correct hash location, but it always seems to be one element too high on the page. This issue occurs even though the scrolling functionality is working fine. For instance, if my ...

Swipe to modify Array

Currently, I am in the process of developing an application that features a Swipe card interface using both AngularJS and the Ionic framework. The functionality of this app will be similar to the one found at . When swiping to accept a card, I want the ar ...

Navigation and Cart Menu Issue: Inability to Expand or Collapse

The website I am currently working on is . I'm facing an issue where the cart menu expands but cannot collapse and the navigation menu does not expand when I resize the window for mobile view. Everything works fine in the normal view of the window. Ho ...

Tips on dividing a div into two separate pages when converting to PDF

I am working on an asp.net MVC project and I need to convert a HTML div into a PDF with two separate pages. Here is an example of my code: HTML Code <div class="row" id="mycanvas"> <p>This is the first part of my content.</p> <p ...

It is not possible to upload files larger than 4mb in ASP.NET MVC3

I am facing an issue with uploading files in ASP.NET MVC3 where I am unable to upload files larger than 4mb. I am currently using jquery.form.js for the file upload process and utilizing ajax to post the form to the server side. It works perfectly fine whe ...

Recording a message from an HTML input using NodeJS and socket.io

I am currently working on a project where I want to log user input from an input box to the NodeJS console. For example, if a user types "Hello world" into the input box and clicks "Send message to console", I want it to show up as "Hello world" in the con ...

The width of the Bootstrap tooltip changes when hovered over

Currently, I am facing a peculiar issue with my angular web-application. Within the application, there is a matrix displaying data. When I hover over the data in this matrix, some basic information about the object pops up. Strangely, every time I hover ov ...

Is the jQuery ajax .done() function being triggered prematurely?

Struggling with a problem here. I'm dealing with this code (simplified): var initializeZasilkovna = function () { // Initialize object window.packetery.initialize(); }; // Check if the object doesn't exist if (!window.packetery) { // It ...

Jasmine spies call through problem detected

I can't seem to get my code to work properly and I keep encountering this error: TypeError: undefined is not an object (evaluating 'GitUser.GetGitUser('test').then') ... Check out the code snippets below: app.controller(&apo ...

What is the best way to apply a specific style based on the book ID or card ID when a click event occurs on a specific card in vue.js

My latest project involves creating a page that displays a variety of books, with the data being fetched from a backend API and presented as cards. Each book card features two button sections: the first section includes "ADD TO BAG" and "WISHLIST" buttons ...

When resizing an anchor tag with a percentage in CSS, the child image width may not scale accordingly

In short, I have multiple draggable images on a map enclosed in anchor tags (<a><img></a>) to enable keyboard dragging. The original image sizes vary, but they are all too large, so I reduced them to 20% of their original sizes using the ...

Incorporating Precision to Decimal Numbers in TypeScript Angular

Having some trouble with this issue and I've tried various solutions without success. This problem is occurring within an Angular project. The requirement is to always display a percentage number with two decimal places, even if the user inputs a who ...