Search code examples
angularjskarma-runnerbrowserifytsify

Angular, Karma, tsify, woes


I'm trying to set up tests, where we are using Angular 1.5, TSify, and Karma. I'm very, close, but I'm running into an issue that I haven't quite got right:

I'm following the setup described here: https://github.com/cmlenz/tsify-test (this example doesn't include angular)

I get an error from angular-mocks: "Cannot set property 'mock' of undefined"

That has to be either a timing thing or a scope thing -- either angular-mocks is loading too soon, or browserify is wrapping up the scope of the angular variable, and mocks can't see it. No idea.

Here are the pertinent parts of my karma.conf.js file:

    frameworks: ['browserify', 'jasmine'],

    files: [
        'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js',
        './node_modules/angular-mocks/angular-mocks.js',
        './modules/**/*.spec.ts'
    ],

    exclude: [],

    preprocessors: {
        '**/*.ts': 'browserify'
    },

    browserify: {
        debug: true,
        plugin: [
            ['tsify']
        ]
    },

This must have something to do with the way I'm loading mocks -- it's not used by my angular app, just the tests, so that must have something to do with it.

Any hints?


Solution

  • angular-mocks needs to be loaded after angular and with your current Karma configuarion, that's not happening - angular is not being loaded until it's required in one of the .ts files upon which one of your .spec.ts files is dependent.

    One solution would be to add an additional file that requires both angular and angular-mocks and to ensure that file precedes the .spec.ts files in Karma's files configuration.

    For example, a file named require-angular-mocks.js could be created:

    require('angular');
    require('angular-mocks');
    

    And could be added to the Karma configuration (replacing the angular-mocks under node_modules):

    files: [
        'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js',
        './require-angular-mocks.js',
        './modules/**/*.spec.ts'
    ],
    
    preprocessors: {
        '**/*.js': 'browserify',
        '**/*.ts': 'browserify'
    },
    

    That should ensure that angular and angular-mocks are loaded in the correct order and are loaded before your specs. Note that if it's a .js file, you'll need another entry in Karma's preprocessors configuration.