2016-12-22 1 views
6

Я получаю следующую ошибку при тестировании углового приложения.Невозможно найти переменную угловатую в spec.js Использование Webpack + Karma + Jasmine для блока AngularJS Тестирование

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

Мое приложение работает отлично с помощью webpack. Также карма дает успех на

expect(true).toBe(true); 

Ниже мой скелет:

enter image description here

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(); 

    }); 
}); 
}); 

карма. конфигурации. 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" 
    ] 
} 

ОШИБКА:

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 [email protected]/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

Пожалуйста, дайте мне знать, если мне что-то не хватает, и если какая-либо другая информация требуется.

Заранее спасибо.

ответ

0

Включите вашу угловую библиотеку и исходные файлы в

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

вы должны добавить угловую библиотеку для выполнения тестирования кармы, а также исходные файлы.

+0

Я пробовал, но не помогал. Я также включил эти файлы в abc.js, которые, в свою очередь, в комплекте с webpack, я думаю. –

+0

включают их отдельно –

+0

Я пробовал включать угловые и угловые-mocks здесь, но он не может найти мой код. Мои файлы находятся в машинописном тексте. wespack ts-loader используется для транспиляции. Почему я использовал webpack-карму. Есть ли способ напрямую помещать файлы .ts здесь, чтобы карма могла их выполнить. –

Смежные вопросы