Issue with running tests in karma-webpack

update: I recently upgraded from karma-webpack 3.0.5 to 4.0.0-rc.2, and encountered some errors. Initially, there was an issue with angular not being defined due to incorrect importing of the home.spec.js file in the tests.bundle.spec. After rectifying this mistake by relying on context for importing instead, my tests started running successfully. I will post a detailed solution once allowed by Stack Overflow.

I suspect that karma is not loading my test bundle file even though webpack generates the bundle.

No console.logs are visible from either tests.bundle.spec.js or home.spec.js. Even with singleRun=false, checking the Chrome console after a refresh shows that the tests.bundle.spec.js file loads but isn't referenced in the html file. Only socket.io.js and karma.js scripts are included in the page.

On debugging through Chrome DevTools, the tests.bundle.spec.js bundle loads but none of the modules inside it run. Setting breakpoints within test scripts and even in the code for tests.bundle.spec.js did not trigger any breakpoints. Karma fails to initialize these modules as expected. Breakpoints within the __webpack_require__ function also remain untapped, indicating that modules aren't required/imported.

The bundling structure and configuration are as follows:

Folder Structure:

-src
--app
---home
----home.js
----home.spec.js
--tests.bundle.spec.js
karma.conf.js
webpack.test.js

karma.conf.js

// Karma Configurations
var webpackConfig = require('./webpack.test.js');

module.exports = function (config) {
    process.env.BABEL_ENV = 'karma';

    config.set({

        basePath: '',
        frameworks: ['jasmine'],

        // files to load
        files: [
            {
                pattern: './src/tests.bundle.spec.js',
                watched: false
            }
        ],

        // plugins
        plugins: [
            'karma-webpack',
            'karma-jasmine',
            'karma-sourcemap-loader',
            'karma-chrome-launcher'
        ],

        preprocessors: {
            './src/tests.bundle.spec.js': ['webpack', 'sourcemap']
        },

        // Webpack config
        webpack: webpackConfig,
        webpackServer: {
            noInfo: false
        },

        reporters: ['progress'],

        port: 9876,

        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,

        browsers: [
            'Chrome'
        ],
        singleRun: false,
        concurrency: Infinity
    })
}

webpack.test.js

// Webpack Testing Configuration
const webpack = require("webpack");
const path = require('path');

// Plugins and loader rules
module.exports = {
    // Mode and source mapping 
    mode: 'development',
    devtool: 'eval-source-map',
    
    entry: {
        app: path.resolve(__dirname, './src/index.js')
    },
    output: {
        path: path.resolve(__dirname, './build_app/'),
        filename: 'app-[name].js',
        chunkFilename: 'app-vendors.[chunkhash].js'
    },
    
    module: {
        // Loader rules for different file types
        rules: [
            // JavaScript source files
            {
                test: /\.js$/,
                exclude: /(node_modules)(\.spec\.js$)/,
                rules : [
                    { loader: 'babel-loader' },
                    {
                        loader: 'eslint-loader',
                        options: {
                            emitError: true,
                            emitWarning: true,
                            failOnError: true,
                            globals: ['_', 'angular', 'lrenums', 'readJSON']
                        }
                    }
                ]
            },
            
            // Templates, LESS, CSS, Images, Fonts etc.
            // ...More rules here...
        ]
    },
    
    // Code optimization settings
    optimization: {
        namedChunks: true,
        splitChunks: {
            chunks: "all",
            minSize: 0,
            cacheGroups: {
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    priority: -10,
                    chunks: 'all',
                    minSize: 0
                }
            }
        }
    },
    
    // Additional plugins
    plugins: [
        new CleanWebpackPlugin(['build_app'], { verbose: true, beforeEmit: true }),
        new HtmlWebpackPlugin({ template: './src/index.php', filename: 'index.php', inject: 'head' }),
        new webpack.ProvidePlugin({ _: 'underscore' })
    ]
};

tests.bundle.spec.js

// Test Bundle File
const context = require.context('./', true, /.+home\.spec\.js$/);

console.log('==============================');
console.log(context.keys());

context.keys().forEach(function(key) {
    context(key);
});

home.spec.js

// Home Specification File
require('angular');
require('angular-mocks');
import './home.js';

describe('home section', function () {

    it('should run test', inject(function () {
        expect(1).toEqual(1);
    });
}

Upon running tests, the result is displayed as

Executed 0 of 0 ERROR (0.001 secs / 0 secs)

Answer №1

I encountered a problem with my karma-webpack-config where optimization.splitChunks was causing issues. Once I removed it, my tests started working properly.

Answer №2

Make sure to include the following line in your karma.conf.js file:

callback: function(){window.__karma__.start()}

Answer №3

Encountered a similar issue while upgrading to webpack 5. During test execution: 0 of 0. Instead of seeking help right away, I took the initiative to create a repository https://github.com/svenbluege/karma-with-webpack-5-test and managed to find the solution there.

The resolution is rather straightforward. You simply need to disable chunking like so:

 webpack: {
  // webpack configuration => makes karma-webpack work!
  optimization: {
    runtimeChunk: false,
    splitChunks: false
  },
  module: {
    rules: [

By default, karma-webpack has chunking enabled. Special thanks to Johannes for providing the helpful tip ()!

Answer №4

After some troubleshooting, I was able to resolve the issue on my own. My apologies for the delay in updating this post with the solution.

Upon following another suggestion, I decided to upgrade from karma-webpack 3.0.5 to 4.0.0-rc.2. However, this led to actual errors being thrown. Specifically, I encountered an error stating that angular was not defined. It turned out that I had mistakenly imported my home.spec.js file from the tests.bundle.spec file instead of relying on the context to import it (a mistake made during debugging). Once I removed the extra import, all my tests ran successfully!

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

Is there a way to set up the application that consumes an npm module with a private git url to strictly utilize files exclusively from the module's dist folder?

In my angular application, I encountered an issue with angular-cli not supporting the creation of a library. To work around this, I opted to use the popular git project found at https://github.com/jvandemo/generator-angular2-library for creating my library ...

What is the process for updating the values of Kendo Grid row elements by utilizing data from an external combobox?

I am currently working with a kendo grid that utilizes the roweditor function, allowing users to edit values of networks labeled as network1, network2, and network3 within the grid - let's refer to this as gridNetwork. On the same page, there is also ...

What is the best way to incorporate tinymce into webpack?

I am facing an issue with integrating tinymce with webpack. It assigns a property called tinymce to window, so one solution is to use the following syntax to require() it (as explained in the bottom of the EXPORTING section of the webpack documentation): ...

Testing Angular 2 components with material icons and images

Recently, I finished creating a unique component that showcases an image, material icons, and a custom directive known as ticker. This directive allows for scrolling text if it exceeds the width of the element. https://i.stack.imgur.com/GpDSr.png My next ...

Whenever I run "npm run build-dev" in Webpack with JavaScript, the browser continuously refreshes

I've been working on familiarizing myself with webpack lately. I've managed to convert everything to load modules and plugins, and it's all working fine when I use "npm run build-prod". Even when I use liveServer, the HTML loads properly. Ho ...

How can we bring in a function into a Vue component?

I'm currently facing an issue with importing a single function into my Vue component. To tackle this problem, I separated the function into its own js file: randomId.js: exports.randomId = () => //My function ... Within my Vue component, I attem ...

The ng-model in Angular is unable to capture the initial input value on load

I am currently using a window onload script to obtain longitude and latitude data and pass them to hidden input values. $(function() { window.onload = getLocation; var geo = navigator.geolocation; function getLocation() { if (geo) { geo ...

Can AngularUI typeahead be used with the orderBy function?

This query is connected to a previous inquiry I made. You can find it here. I have successfully implemented AngularUI Typeahead. However, my orderBy filter seems ineffective. The select box arranges items correctly (distance is a custom function): <s ...

Controller variable in Angular not being updated in view

I am facing an issue with my Angular view not updating after changing a value in the controller through a partial. Interestingly, when I use console.log to log the changed values, everything seems to work fine. TestController $scope.testitem = 0; $sco ...

AngularJS chatbox widget for interactive communication

Currently, I am in the process of developing the back-end for a web application utilizing angularJS. One of the key features is allowing users to communicate with each other through a pop-up chat box similar to those found in Gmail or Facebook. My goal is ...

Exploring the benefits of employing infinitescroll within AngularJS

I am trying to implement a $http function in my codebase that fetches data from the server. My goal is to dynamically load more data as the user scrolls, but I'm facing some challenges in making this functionality work seamlessly. Below is the implem ...

Guide on incorporating the ":gt" filter from sizzle into vanilla javascript

I am currently working on adapting a jQuery plugin to be compatible with the AngularJS JQlite API, but I have encountered some challenges along the way. Here is an overview of the plugin: (function (e) { var $product = $('#product'), ...

Angular form displayed on the screen

I'm having trouble finding a solution to this issue, as the form data is not being output. var app = angular.module('myApp', []); app.controller('mainController', ['$scope', function($scope) { $scope.update = funct ...

Standardize date formatting in AngularJS

Retrieve the date in the shared format: {{ dateValue | date:{{dateFormat}} }} The following service is provided: app.service('formatting', function() { var format = new Object(); format.dateFormat = 'medium' var ...

Are you looking to conduct comprehensive UI tests for a team-based web application?

Our web application is designed for collaborative use, so actions by one user in their browser affect another user's experience. A prime example of this functionality can be seen in our chat room feature. The technology stack we are currently using i ...

What is the process for including a new path in webpack configuration?

After setting up a project using vue-cli with the command vue init webpack myProject, I found that several files and folders were created within the myProject folder. To run the project, I used the command npm run dev. Now, I am looking to expand my proje ...

What is the best way to display compiled Transcluded HTML in Angular?

I am facing a challenge in trying to display customized HTML content using Angular directives for nesting divs multiple times. When I execute the code below, the transcluded tag is displayed correctly but the browser output shows the string text " ". I att ...

Angular-ui-bootstrap modal failing to display provided data

I have been working on implementing model data into a modal window that opens. The data is passed through a $http.post success and also in failure then() with different titles and button texts. Several data points are being passed to the modal: //.then(){ ...

Using AngularJS, you can display repeated elements in a single textarea by utilizing

--> I want to be able to input data into a textarea using just one textarea element. --> The reason for this is so that when the data in MySQL is updated, I can type new data in the textarea while still keeping the existing data. I have tried using ng-re ...

What are the steps to inject the npm package called lodash as a dependency injection in AngularJS for the angular-google-maps module with the help

I have set up my angular application using npm as the package manager and Browserify to manage libraries. The specific package I am using is angular-google-maps from http://angular-ui.github.io/angular-google-maps. An error message I encountered is: Refe ...