简体   繁体   中英

Can't find variable angular in spec.js Using Webpack+Karma+Jasmine for AngularJS unit Testing

I am getting following error while testing angular app.

Can't find variable: angular in spec/abc.spec.js

My app is running fine with webpack. Also karma gives success on

expect(true).toBe(true);

Following is my skeleton:

在此输入图像描述

abc.ts

var angular = require('angular');
var angular_mocks = require('angular-mocks');
var specs = require('../spec/abc.spec.js');

var myApp = angular.module('myApp',[]);

myApp.controller('MyController', function($scope) {
  $scope.spices = [{"name":"pasilla", "spiciness":"mild"},
                   {"name":"jalapeno", "spiciness":"hot hot hot!"},
                   {"name":"habanero", "spiciness":"LAVA HOT!!"}];
  $scope.spice = "habanero";
});

abc.spec.js

describe('myController function', function () {

describe('myController', function () {
    var $scope;

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

    beforeEach(inject(function ($rootScope, $controller) {
        $scope = $rootScope.$new();
        $controller('MyController', {$scope: $scope});
    }));

    it('should create "spices" model with 3 spices', function () {
        expect($scope.spices.length).toBe(3);
    });

    it('should set the default value of spice', function () {
        expect($scope.spice).toBe('habanero');

    });

    it('should set the default value of spice', function () {
        expect(angular).toBeDefined();

    });
});
});

karma.config.js

// Karma configuration
// Generated on Wed Dec 21 2016 19:28:26 GMT+0530 (India Standard Time)

var webConfig = require('./karma.conf')

module.exports = function(config) {
config.set({

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


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


// list of files / patterns to load in the browser
files: [

  'spec/*.js'
],


// list of files to exclude
exclude: [
'src/bundle.js'
],

webpack: webConfig,

webpackMiddleware: {
  stats: 'errors-only'
},

// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
    'src/*.js': ['coverage', 'webpack']
},


// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress','coverage'],


coverageReporter: {
  type : 'html',
  dir : 'coverage/'
},


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


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


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

webpack.config.js

var webConfig = {

entry: './src/abc',
output:{
    path: 'src',
    filename:'bundle.js'
},

resolve: {
    root: ['src', "node_modules"],
    extensions: ['', '.ts', '.js']
},

modules: {
    loaders: [
        {
            test:/\.ts?$/,
            loader:'ts-loader'
        }
    ]
}
}

module.exports = webConfig;

tsconfig.js

{
"compilerOptions": {
"target": "es5",
"module": "amd",
"moduleResolution": "node",
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
},
"exclude": [
   "typings",
   "node_modules"
  ]
}

ERROR:

C:\Users\namankheterpal\IdeaProjects\ngwk>karma start

webpack: bundle is now VALID.
22 12 2016 13:55:36.125:WARN [karma]: No captured browser, open http://localhost:9876/
22 12 2016 13:55:36.137:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
22 12 2016 13:55:36.138:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
22 12 2016 13:55:36.151:INFO [launcher]: Starting browser PhantomJS
22 12 2016 13:55:37.906:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket /#GxGMuAyLHkfyOc9NAAAA with id 40162084
PhantomJS 2.1.1 (Windows 8 0.0.0) myController function myController encountered a declaration exception FAILED
    ReferenceError: Can't find variable: angular in spec/abc.spec.js (line 6)
    spec/abc.spec.js:6:23
    spec/abc.spec.js:3:11
    global code@spec/abc.spec.js:1:9
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.006 secs / 0.001 secs)

Reffrence https://github.com/webpack/karma-webpack

Please let me know if I am missing something and if any other info is required.

Thanks in advance.

Include your angular library and your source files at

files: [
   'location/angular.min.js'
'spec/*.js'
],

you have to add angular library to execute karma testing and also your source files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM