Karma Webpack Jasmine Unit Testing not working
Asked Answered
B

2

1

I am trying to setup testing with Karma, Jasmine, Webpack in AngularJS. My webpack is working fine and I can run my website using npm start

A simple test works fine but the moment I try to add my app.js everything goes downhill.

I have tried many many many searches and many solutions. Please dont think, I am writing this question the moment I hit a deadend. I have spent all day today just googling and find possible solutions.

There is my karma.conf.js file

// 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({

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

    frameworks: ['jasmine'],

    // ... normal karma configuration
    files: [
        './node_modules/jasmine-core/lib/jasmine-core/jasmine.js',
        './node_modules/angular/angular.js',                                        // angular
        './node_modules/angular-mocks/angular-mocks.js',                            // loads our modules for tests

        // all files for test
        './resources/assets/js/auth/app.js',
        './resources/assets/js/account/invoices/*.spec.js',
    ],

    preprocessors: {
        // add webpack as preprocessor
        './resources/assets/js/account/invoices/*.spec.js':     ['webpack'],
    },

    webpack: {
        // webpack configuration
        webpackConfig
    },

    webpackMiddleware: {
      // webpack-dev-middleware configuration
      // i. e.
      stats: 'errors-only'
    },

    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // 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_DEBUG,

    // 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: ['Chrome'],

    // 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
  })
}

The test that I have written is

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

    // Load the myApp module, which contains the directive
    beforeEach(angular.mock.module('app'));

    // Store references to $rootScope and $compile
    // so they are available to all tests in this describe block
    beforeEach(inject(function(_$compile_, _$rootScope_){
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    it('Replaces the element with the appropriate content', function() {
        // Compile a piece of HTML containing the directive
        var element = $compile("<dash-list></dash-list>")($rootScope);
        // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
        $rootScope.$digest();
        // Check that the compiled element contains the templated content
        expect(element.html()).toContain("Unpaid");
    });
});

And it fails with this error:

18 09 2017 15:00:18.554:DEBUG [web-server]: serving (cached): project/resources/assets/js/account/invoices/dash.spec.js
18 09 2017 15:00:18.557:DEBUG [web-server]: serving (cached): project/resources/assets/js/account/invoices/add-business.spec.js
18 09 2017 15:00:18.576:DEBUG [web-server]: serving: project/node_modules/karma/static/context.js
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 am using OSX. Technically, webpack should serve the compiled file to Karma. But unexpected token import means that file is not being compiled and served to Karma.

Please help.

I even tried to compile with babel but that didnt go anywhere either. I moved to webpack because we already have webpack config built and project is compiled using webpage.config

UPDATE

To anyone who stubble upon this question, I used the OPTION #1 by Felix. I just included the compiled files in the Karma. It worked like charm.

Webpack auto compile files whenever files are changed, so just adding the output worked fine.

My files array looked like following

files: [
    './node_modules/jasmine-core/lib/jasmine-core/jasmine.js',
    './node_modules/angular/angular.js',                                        // angular
    './node_modules/angular-mocks/angular-mocks.js',                            // loads our modules for tests
    './resources/assets/js/account/stripe.spec.js',
    './node_modules/angular-stripe/index.js',
    './node_modules/angular-stripe-checkout/angular-stripe-checkout.js',

    // all files for test
    './public/assets/vendor.bundle.js',
    'http://localhost:8080/assets/account.js',
    './resources/assets/js/account/invoices/*.spec.js',

I had to use http for the 2nd option unfortunately but it is working fine.

Bedplate answered 18/9, 2017 at 5:9 Comment(0)
G
1

Pay attention that in you karma file, you pass to webpack only to run on the specs. So your app is not processed.

You have 2 options:

  1. Add you app webpack bundle to karma manually.
  2. Import the "app" from within the specs, in that way webpack will start from the specs, and import the app for you.
Gretta answered 18/9, 2017 at 5:19 Comment(14)
Thanks for your reply. I added this line at the top of my dash.spec.tst import app from '../../auth/app'; Error is still the same Chrome 60.0.3112 (Mac OS X 10.12.6) ERROR Uncaught SyntaxError: Unexpected token import at resources/assets/js/auth/app.js:1 in file app.jsBedplate
Instead of loading that file ./resources/assets/js/auth/app.js in your Karma config, you will need to load the app bundle itself. Or add another section to preprocessors for the app.jsGretta
Added another section in the preprocessors. Still no luck. preprocessors: { './resources/assets/js/auth/app.js': ['webpack'], './resources/assets/js/account/invoices/*.spec.js': ['webpack'], },Bedplate
Can you share your webpack config?Gretta
Can you elaborate on option 1. How to achieve that? Add you app webpack bundle to karma manually. I can try that.Bedplate
Added webpack config to the question also. Thanks in advance.Bedplate
When you run the app on the browser, you add the app bundle to the html file, put that path instead of the app.js that you put.Gretta
I have done that. files: [..., './public/assets/vendor.bundle.js', './resources/assets/js/account/invoices/*.spec.js' ], But the error now is serving (cached): /public/assets/vendor.bundle.js Chrome 60.0.3112 (Mac OS X 10.12.6) Unit testing Dash Replaces the element with the appropriate content FAILED Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.Bedplate
Ok, now it looks that the vendor.bundle.js is not contains the angular module, are you sure that vendor.bundle.js is the right file?Gretta
From your webpack config, the entry file is auth: './js/auth/app.js', so it should be auth.bundle.js, or something similarGretta
There is only one js file vendor.bundle.js in the public/assets/ folder. It is of size 8.3MB. There is no other js file. It should have everything.Bedplate
I think you are correct here. vendor.bundle.js is not the compiled file for angular. But there is no other file. If this is on the file then one. There is no other js file.Bedplate
Let us continue this discussion in chat.Bedplate
Updated my question to include the answer that worked for me.Bedplate
M
1

karma problem to install: ERROR

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

To solve this error following command is useful for it. Its Solve for me...

npm cache clean --force

Myrnamyrobalan answered 2/8, 2018 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.