Encountering an unexpected token error - Karma and Webpack testing having trouble with the forward slash symbol

I have been facing some issues while setting up my angular tests. The error message I keep getting is:

PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  SyntaxError: Unexpected token '/'
  at app/components/dropdown/dropdown.spec.ts:1

PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
  SyntaxError: Unexpected token '/'
  at app/components/dropdown/dropdown.spec.ts:1

I have checked my files multiple times but can't seem to find what might be causing this issue. Below are the files I am using:

karma.conf.js

var WebpackConfig = require('./webpack.config.js');

// Karma configuration
// Generated on Wed Dec 30 2015 11:13:38 GMT-0500 (EST)

module.exports = function (config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '.',

        files: [
            'app/**/*.spec.ts'
        ],


        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha', 'chai'],


        // list of files to exclude
        exclude: [
            'node_modules'
        ],


        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'dots'],


        // web server port
        port: 9876,


        // enable / disable colors in the output (reporters and logs)
        colors: true,


        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,


        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,


        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['PhantomJS'],


        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,

        preprocessors: {
            'app/**/*.spec.ts': ['webpack']
        },

        webpack: WebpackConfig,

        webpackMiddleware: {
            noInfo: true
        },

        plugins: [
            require('karma-mocha'),
            require('karma-chai'),
            require('karma-phantomjs-launcher'),
            require('karma-webpack')
        ]
    });
};

webpack.config.js

var Loaders = require('./webpack/loaders');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        'bundle': 'app/core/bootstrap.ts'
    },
    output: {
        path: 'public',
        library: '[name]',
        filename: '[name].js'
    },
    resolve: {
        root: __dirname,
        extensions: ['', '.ts', '.js', '.json']
    },
    resolveLoader: {
        modulesDirectories: ['node_modules']
    },
    devtool: 'source-map',
    plugins: [
        new HtmlWebpackPlugin({
            template: 'app/index.html',
            inject: 'body',
            hash: true
        })
    ],
    module: {
        loaders: Loaders
    }
};

Currently, I only have one test named: dropdown.spec.ts

import '../../core/tests.ts';
import {chai} from '../../core/tests.ts';

var expect = chai.expect;

describe('Unit tests for DropDown component', () => {

    describe('2 + 4', () => {

        it('should be 6', (done) => {
            expect(2 + 4).to.equal(6);
            done();
        }); 

        it('should not be 7', (done) => {
            expect(2 + 4).to.not.equals(7);
            done();
        });

        it('should be 10', (done) => {
            expect(6 + 4).to.equal(10);
            done();
        });
    });

});

tests.ts

require('../../node_modules/mocha/mocha.js');
export var chai = require('../../node_modules/chai/chai.js');

package.json

{
  "name": "proj",
  "version": "0.0.1-beta2",
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "angular-mocks": "^1.5.3",
    // All the other dependencies ...
    
  },
  "dependencies": {
    "angular": "^1.5.8",
    "angular-ui-router": "^0.3.1",
    "socket.io-client": "^1.5.0"
  },
  "optionalDependencies": {
    "fsevents": "1.0.14"
  }
}

Answer №1

When utilizing the "library" parameter in your webpack.config.js file, the global variable is assigned a name based on the file path and name. If you inspect the browser console, you will observe:

To rectify this issue, modify your karma.config.js file as follows:

var WebpackConfiguration = require('./webpack.config.js');
WebpackConfiguration.output.library = false;

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

Can you explain the role of the next() function in middleware/routes following the app.use(express.static(...)) in Express

When dealing with serving static assets generated from React source code using npm run build, the following method can be used: app.use('/', express.static(path.join(__dirname, 'apps', 'home', 'build'))) To protect ...

Error: Unable to find the definition for Image (Next.js)

This new component in my next js project allows me to write a quote on an image and display it on the canvas. However, I am encountering an issue with the Image() function in JavaScript which typically runs on the browser. It seems that Next.js first execu ...

leveraging the localStorage feature in a for-in iteration

I am new to stackOverflow, although I have browsed the forums for help in the past. However, this time I couldn't find a solution to my current issue, so I decided to create an account and seek assistance. The problem at hand is related to a workout ...

Rendering with Next.js script

Within my Next.js project, there is a script implemented to render a widget. The code for this script looks like: <a className="e-widget no-button xdga generic-loader" href="https://example" rel="no ...

Guide to setting a default child route in react-router and updating the URL as needed

Currently, I am utilizing react-router v3 and have a segment of my routing code as follows: ... <Route path='dashboard' component={Dashboard}> <Route path='overview' component={Overview}/> <Route path='scan&apo ...

Sharing a variable with JavaScript within an OnClick event to update a progress bar in C#

When I click on a button, a JavaScript function is launched to create a progress bar. <asp:Button ID="btn_tel" runat="server" CausesValidation="False" OnClick="btn_telefono" Text="Check" CssClass="button" OnClientClick="move()" /></div> The f ...

Encountered an error with @angular-cli/ast-tools during the installation of angular-cli on a Mac running OS X (El Capitan

While attempting to install the latest version of @angular-cli on my Mac OS X (El Capitan) using the command sudo npm install -g @angular-cli@latest, I encountered the following error: Darwin 15.4.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" ...

What is the process for modifying a task on my to-do list with a long press?

I'm currently working on implementing a task update feature in my project. However, I've encountered an issue where the prompt only works in the browser environment. Is there a way to make this work in React Native or are there any alternative so ...

Trie-based autocomplete functionality

I am currently creating an auto-completion script and I'm considering utilizing a trie data structure. My main concern is that I want all possible matches to be returned. For instance, when I type in the letter r, I expect to see all entries beginning ...

The method models.User.fromURI is unsuccessful

When I try to call models.User.fromURI as shown below: models.User.fromURI("spotify:user:" + user, function (user) { $(div).html("<b ><a style=\"color:#FFFFFF\" href=\"spotify:user:" + user.username + "\">" + us ...

Trouble importing class using path alias in Typescript encountered

I am currently experimenting with Typescript and OvernightJS and encountering an issue while trying to import a class into my controller. I received an error message that says: Error: Cannot find module '@Models/company' Interestingly, when I ...

Is there a way to prevent Chrome from automatically toggling into debug mode?

When the debugging window is open, the debugger seems to start running through lines automatically without any breakpoints being set. I attempted to use the "Deactivate breakpoints" button, but it had no effect whether it was enabled or disabled. This is ...

What is the best practice for npm/yarn workspaces: should packages use src or dist for consumption

Our frontend app will be structured within a monorepo. The plan is to organize react UI components into a package folder located at "/packages/ui-components", while keeping the app itself in an "/apps/app" folder. The goal is to have the app import and con ...

Error encountered: Mongodb db.collection.find() function is not successfully retrieving data, whereas the collection.insert() function

Working with node.js/express and utilizing a Mongodb database to store various data sets. The functionality for adding, editing, and deleting data on a webpage is functioning properly. For instance, the code snippet for adding data is as follows: router. ...

Navigating to the bottom of a page once an element is displayed (with react-slidedown)

I'm facing a bit of a challenge here that I haven't been able to resolve yet. So, I have this optin form that is revealed upon clicking on a link. The reveal effect is achieved using react-slidedown. The issue I'm encountering is that when ...

AngularJS: When the expression is evaluated, it is showing up as the literal {{expression}} text instead of

Resolved: With the help of @Sajeetharan, it was pinpointed that the function GenerateRef was faulty and causing the issue. Although this is a common query, I have not had success in resolving my problem with displaying {{}} to show the outcome. I am atte ...

Ajax is coming back with a value that is not defined

Currently, I am working on a search function that is responsible for searching a name from the database. When the user clicks "add", the selected item should appear below the search field so that it can be saved in the database. However, I am encountering ...

Building a Vue application with customized authentication for the Google Calendar API in JavaScript

Struggling with understanding the migration from GAPI to GIS in Vue? Google has provided a helpful document on this topic: https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#server-side-web-apps Attempting to implement code from the ...

Issues with WSS not functioning properly on HTTPS during video recording

Overview of Application Implementation Our application requires video recording functionality. To achieve this, we decided to use the MediaRecorder API available at https://developer.mozilla.org/en/docs/Web/API/MediaRecorder_API. We are utilizing the get ...

Make sure to wait for the VueX value to be fully loaded before loading the component

Whenever a user attempts to directly navigate and load a component URL, a HTTP call is initiated within my Vuex actions. This call will set a value in the state once it has been resolved. I am looking to prevent my component from loading until the HTTP ca ...