question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

karma-webpack seems to break angular unit tests

See original GitHub issue

I have recently converted a project I am working on over to webpack, including my unit tests for the Angular front-end. I have some unit tests written for some directives with custom transclusion/jquery/jqlite functionality in the link functions which passes in a webpack-less testing environment, yet when tested with karma-webpack they do not pass. Allow me to demonstrate:

Standard karma.conf.js

// Reference: http://karma-runner.github.io/0.12/config/configuration-file.html
module.exports = function(config) {
  config.set({

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


    files : [

        'public/tests.bundle.js'
    ],


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


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {

        'public/tests.bundle.js' : ['webpack', 'sourcemap']
    },


    // . . .


    webpack: {

        // Just do inline source maps instead of the default
        devtool: 'inline-source-map',

        module: { 

            loaders: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader'
                },
            ],
        }
    }
  });
};

Test bundle

// Doesn't work with or without this line
import 'jquery';

import 'angular';
import 'angular-mocks/angular-mocks';

var testsContext = require.context('.', true, /.+\.spec\.js$/);

testsContext.keys().forEach(testsContext);

Angular Directive in ES6

import directiveFactory from '../../directivefactory.js';

// ## Directive Definition
class pageHeader {

    constructor() {

        this.template =
        `
            <div class="d5-page-header-wrapper">

                <div class="d5-page-header">

                    <!-- Main page header text -->
                    <!-- component user content insertion point 1 -->
                    <span class="text-main" transclude-id="header"></span>

                    <!-- Small page header text -->
                    <!-- component user content insertion point 2 -->
                    <span class="text-small" transclude-id="small"></span>

                    <hr class="break">

                    <!-- Page header text lead -->
                    <!-- component user content insertion point 3 -->
                    <span class="text-lead" transclude-id="lead"></span>

                    <!-- Custom navigation button -->
                    <button class="btn btn-custom btn-block btn-lg">

                        Jump to Collections <span class="glyphicon
                            glyphicon-arrow-down"></span>

                    </button>

                </div>

            </div>
        `;
        this.restrict = 'E';
        this.scope = {};
        this.bindToController = {

        };
        this.transclude = true;
        this.controller = PageHeaderController;
        this.controllerAs = 'vm';
    }

    // ###Optional Link Function
    link (scope, elem, attrs, ctrl, transclude) {

        transclude ((clone) => {

            angular.forEach(clone, (cloneEl, value) => {

                // If the clone element has attributes...
                if(cloneEl.attributes) {

                    // Get desired target ID...
                    var tId = cloneEl.attributes["transclude-to"].value;

                    // Find target element with that ID...
                    var target = elem.find('[transclude-id="' + tId + '"]');

                    // Append element to target
                    target.append(cloneEl);
                }
            });
        });
    }
}

export default ['pageHeader', directiveFactory(pageHeader)];

Unit Test

describe('page header directive', () => {

    let elem, scope;

    // Mock our page-header directive
    beforeEach(angular.mock.module(pageHeader));

    beforeEach(angular.mock.inject(($rootScope, $compile) => {

        // Define the directive markup to test with
        elem = angular.element(
            `
            <div>

                <page-header>

                    <span transclude-to="header">

                        Test Header

                    </span>

                    <span transclude-to="small">

                        Test Small Header

                    </span>

                    <span transclude-to="lead">

                        Test Lead Content

                    </span>

                </page-header>

            </div>
            `
        );

        scope = $rootScope.$new();

        $compile(elem)(scope);

        scope.$digest();
    }));

    describe('link transclusion function', () => {

        it("should create a main header element containing the component " +
            "user's markup", () => {

            let items = elem.find('.text-main');

            console.log(items);

            // FAIL
            expect(items.eq(0).text()).toContain('Test Header');
        });
    });
});

I am not sure if this is the right place to post this or not, but it seems the problem lies in my implementation or karma-webpack as the code works in the browser as it should. In any case, I’d appreciate the help with the matter.

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:2
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
mattzaitleycommented, Dec 1, 2015

I’m having similar problems - any luck solving @datatypevoid?

0reactions
joshwienscommented, Jan 19, 2017

If I can get a minimal repo where this issue is reproducible, i’ll get it into the v3 milestone and see that it’s addressed.

Something like this - https://github.com/Silviu-Marian/karma-webpack-pr69 would be extremely helpful.

Read more comments on GitHub >

github_iconTop Results From Across the Web

karma-webpack seems to break angular unit tests #73 - GitHub
I have recently converted a project I am working on over to webpack, including my unit tests for the Angular front-end.
Read more >
Unit Testing with karma in Angular 4 with Webpack
Here is my karma.config.js file - module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine'], ...
Read more >
Testing - ts - GUIDE - Angular
The karma test runner is ideal for writing and running unit tests while developing the application. It can be an integral part of...
Read more >
AngularJS with Webpack - Testing with Karma, Mocha, and Chai
Webpack simplifies things considerably. In this lesson you'll see how to test an Angular application built with Webpack using karma, mocha, and chai....
Read more >
Unit testing JavaScript with Karma in 2021. Starting point
Karma was born in the era of AngularJS. ... Single run means that when tests are finished karma would stop and to ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found