Issues with executing Unit Tests in Karma using Webpack and Jasmine

Trying to set up testing with Karma, Jasmine, and Webpack in AngularJS has been quite a journey for me. While my webpack is functioning smoothly and I can run my website using npm start, things take a turn when I attempt to include my app.js.

Despite numerous searches and attempts at solutions, integrating app.js seems to be causing some issues. It's not like I've given up easily; I've dedicated an entire day to googling and exploring potential fixes.

In my karma.conf.js file, you'll find the following configuration:


// Karma configuration
// Generated on Mon Sep 18 2017 09:27:36 GMT+1000 (AEST)

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

module.exports = function(config) {
  config.set({
    // various settings here...
  })
}

The unit test I've created looks like this:


describe('Unit testing Dash', function() {
    var $compile,
        $rootScope;

    beforeEach(angular.mock.module('app'));

    beforeEach(inject(function(_$compile_, _$rootScope_){
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    it('Replaces the element with the appropriate content', function() {
        var element = $compile("<dash-list></dash-list>")($rootScope);
        $rootScope.$digest();
        expect(element.html()).toContain("Unpaid");
    });
});

Unfortunately, running this test results in the following error:


Chrome 60.0.3112 (Mac OS X 10.12.6) ERROR
  Uncaught SyntaxError: Unexpected token import
  at resources/assets/js/auth/app.js:1

I'm working on OSX and logically, webpack should serve the compiled file to Karma. However, the 'unexpected token import' suggests that the file isn't being compiled and served properly.

If anyone comes across this question, know that I followed Felix's OPTION #1, by directly including the compiled files in Karma. This workaround proved to be effective as webpack automatically compiles files whenever changes are made.

My updated files array now includes:


files: [
    './node_modules/jasmine-core/lib/jasmine-core/jasmine.js',
    './node_modules/angular/angular.js',
    './node_modules/angular-mocks/angular-mocks.js',
    './resources/assets/js/account/stripe.spec.js',
    './node_modules/angular-stripe/index.js',
    './node_modules/angular-stripe-checkout/angular-stripe-checkout.js',
    './public/assets/vendor.bundle.js',
    'http://localhost:8080/assets/account.js',
    './resources/assets/js/account/invoices/*.spec.js',

Even though the http usage was necessary for the second option, everything seems to be functioning seamlessly now.

Answer №1

It's important to note that in your karma configuration file, you are only instructing webpack to run on the specs and not process your app code.

You can choose from 2 alternatives:

  1. Manually add your app webpack bundle to karma.
  2. Import the "app" module from within the specs. This will prompt webpack to start from the specs and automatically import the app for you.

Answer №2

Encountering a challenging karma issue during installation: ERROR

bpack-2.0.3.tgz"}},"2.0.4":{"name":"karma-webpack","version":"2.0.4",

To successfully resolve this error, the following command proved to be highly effective in my case...

npm cache verify --force

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

"Troubleshooting Error: When accessing a property in AngularJS,

My goal is to retrieve a date value. However, I encounter an error message saying 'Cannot read property 'NTLI' of undefined' whenever the checkbox is unchecked and the date picker is invisible. Strangely enough, everything works fine wh ...

The source 'http://localhost:3000' is not authorized to access the Twitter API

I am working on a web application that utilizes the Twitter API REST. On one of my pages, I have a list of Twitter accounts and a button to add a new account. When this button is clicked, it triggers a function in the Angular controller: // Function to ...

Animating just the width in AngularJS: A Step-by-Step Guide

I am struggling to find suitable examples demonstrating how to animate the width of an element in Angular using the new animation feature. In my app, I have a side drawer that I want to expand or close when the user clicks a button. However, when using ng ...

Enhancing ng-model by clicking on a list item

I currently have a textbox on my webpage. <input ng-model="meetingData.client.ClientName" id='txtClient' placeholder="Add new client" type="text"> along with a list of items that I want to interact with. Is there a ...

Enhancing angular $resource requests with custom headers

I'm currently facing a challenge in adding a header to all HTTP requests sent by Angular ($resource is used to interact with a REST server) in order to include Basic Auth information collected from user input (username/password). Initially, I attempt ...

Validation messages in an Angular application using Typescript are failing to display or disappear sporadically when applied to an HTML form that has

I am currently working on a simple app that retrieves website content from a CMS [Umbraco]. After making an Ajax call, the form comes back to me as plain HTML. I then append the form to the page and use the Angular $compile service to compile the result. T ...

Unlocking the Power of $http and Stream Fusion

I'm interested in accessing the public stream of App.net. However, when I attempt to retrieve it using a simple $http.get(), I only receive one response. $http .get('https://alpha-api.app.net/stream/0/posts/stream/global') .success(func ...

Triggering an event when the cursor enters a specific div/span/a element and again when the cursor exits the element

Here's the scenario - Imagine a contenteditable element with text inside. I'm working on creating a tagging feature similar to Twitter's mention tagging when someone types '@'. As the user types, a popover appears with suggestion ...

Discover the method of accessing items pushed into an empty array within a view

Is there a way to retrieve the pushed array in the view section? $scope.addCart = function(){ $scope.viewDetails=[]; $scope.viewDetails.push({"name":"mobile"}); $scope.viewDetails.push({"price":"23"}); ...

Using the scope attribute with $watch does not effectively monitor changes to the model

I'm currently developing a directive designed for <input> that monitors user input. The goal is to reformat the input model object and set a variable as true once a valid phone number has been entered. CountryISO is injected as a constant depen ...

Angular Q for Beginners - Manipulating Service Results

After spending the entire day working on my inaugural Angular app, I have come across a fundamental query. My objective is to design a text field with two strings that describe the current URL route and action in the following format: You are on: {{urlRo ...

Identifying Hashtags with Javascript

I am trying to identify hashtags (#example) in a string using javascript and convert them to <a href='#/tags/example'>example</a> Currently, I have this code: var text = '#hello This is an #example of some text'; text.r ...

Is it possible to engage in peer-to-peer chatting using the Firebase Chat application on a web platform?

I'm currently utilizing a firebase chat application in conjunction with AngularJS. My specific need is for messages to be sent from one user to another user only, without being broadcasted to all users. Are there any methods or frameworks that allow f ...

What is the best way to execute multiple Protractor test suites simultaneously?

Exploring Protractor for the first time. My goal is to run multiple test suites in a sequence. I have a complex angular form with various scenarios, each with its expected results. I want to execute all tests with just one command. Initially, I tried enter ...

Protractor - Issue with clicking on hidden element with "ng-click" attribute

I'm facing an issue with a specific element that I am unable to click using Protractor. Everything was working fine until a few days ago. Technical information: Chrome version: 47.0.2526.106 Protractor version: 2.0 Selenium version: 2.44 CSS &l ...

Showing validation in a Bootstrap modal after it has been closed

I have implemented a form view in AngularJS with a modal from Angular-ui to showcase my form. I am happy with how everything functions, but there is one issue - when I dismiss the form, validation pop-ups appear if the form is not valid. Here is an overvi ...

Displaying Angular charts can enhance the visualization of data by mapping chart labels to the properties of an object

Currently, I am utilizing angularJs Charts which can be found at In my possession is an array of objects that looks something like this: let MyArray = [{a: 1, b: 2,c:3}, {a: 3, b: 4,c:10}, {a: 5, b: 6,c:20}, {a: 7, b: 8,c:30}]; The goal here is to connec ...

What could be causing AngularJS to truncate my URL in the search bar?

Currently, I am in the process of setting up a state provider for a CRUD website. One issue I encountered is that when I navigate to www.mysite.com/posts/mypost, the URL gets shortened to www.mysite.com/mypost and does not trigger the controller as intend ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...

How can I integrate both the ui-bootstrap datepicker and timepicker in an AngularJS application?

I am currently developing a web application that utilizes UI-Bootstrap's datepicker and timepicker directives. The datepicker is set up as a simple popup dialog, while the timepicker appears on the page next to the datepicker. However, I am facing ch ...