Грешка при получаване на AngulaJS + Angular AMD + RequireJS за работа с Karma и Jasmine

Опитвам се да добавя поддръжка за базирано на Karma & Jasmine+Require Js модулно тестване за AngularJS +Angular AMD & RequireJS приложение, което създадох. Разбивам мозъка си около това вече два дни, но все още не съм близо до сключването на сделката.

Продължавам да получавам грешката:

INFO [karma]: Karma v0.12.21 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 36.0.1985 (Mac OS X 10.9.4)]: Connected on socket 8oFHaa2hqJPs0ecgIXCa with id 31963369
Chrome 36.0.1985 (Mac OS X 10.9.4) ERROR: 'There is no timestamp for     ../www/scripts/specs/UserControllerTest.js!'

WARN [web-server]: 404: /www/scripts/specs/UserControllerTest.js
Chrome 36.0.1985 (Mac OS X 10.9.4) ERROR
  Uncaught Error: Script error for: specs/UserControllerTest
  http://requirejs.org/docs/errors.html#scripterror
  at /usr/local/lib/node_modules/requirejs/require.js:141

Моят код е както следва:

  1. Конфигурационният файл на Karma:

    // Karma configuration
    // Generated on Fri Aug 15 2014 20:49:40 GMT+1000 (EST)
    
    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', 'requirejs'],
    
    
    // list of files / patterns to load in the browser
    files: [
     'test-main.js',
     {pattern: 'specs/*.js', included: true}
    ],
    
    
    // list of files to exclude
    exclude: [
    ],
    
    
    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
     preprocessors: {
     },
    
    
     // test results reporter to use
    // possible values: 'dots', 'progress'
    // 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_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: ['Chrome'],
    
    
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
     });
    };
    
  2. Моят файл test-main.js.

     var allTestFiles = [];
     var TEST_REGEXP = /(spec|test)\.js$/i;
    
     var pathToModule = function(path) {
       return path.replace(/^\/base\//, '').replace(/\.js$/, '');
     };
    
     Object.keys(window.__karma__.files).forEach(function(file) {
       if (TEST_REGEXP.test(file)) {
         // Normalize paths to RequireJS module names.
         allTestFiles.push(pathToModule(file));
       }
     });
    
     require.config({
       // Karma serves files under /base, which is the basePath from your config file
       baseUrl: '../www/scripts',
    
       // alias libraries paths
             paths: {
                 'angular': '../libs/angular',
                 'angular-route': '../libs/angular-route',
                 'angular-animate':'../libs/angular-animate',
                 'angular-mocks':'../libs/angular-mocks',
                 'angularAMD': '../libs/angularAMD.min',
                 'Framework7':'../libs/framework7',
                 'UserController':'controller/UserCtrl',
                 'WebCallManager':'services/WebCallManager'
             },
    
             // Add angular modules that does not support AMD out of the box, put it in a shim
             shim: { 
                 'angularAMD': ['angular'],
                 'angular-route': ['angular'],
                 'angular-animate':['angular'],
                 'angular-mocks':['angular'],
                 'Framework7':{exports: 'Framework7'}
             },
    
             //kick start application
             //deps: ['app'],
    
       // dynamically load all test files
       deps: allTestFiles,
    
       // we have to kickoff jasmine, as it is asynchronous
       callback: window.__karma__.start
     });
    
  3. И моят Unit Test е:

         describe('UserController', function () {
    
         var scope,controller;
    
         //mock Application to allow us to inject our own dependencies
         beforeEach(angular.mock.module('app'));
    
    
         //mock the controller for the same reason and include $rootScope and $controller
         beforeEach(angular.mock.inject(function($rootScope, $controller) {
             //create an empty scope
             scope = $rootScope.$new();
             //declare the controller and inject our empty scope
             $controller('UserController', {$scope: scope});
    
           }));
    
    
    
         it('checks the controller name', function () {
             expect(scope.name).toBe('Superhero');
         });        
     });
    

Качих целия си код на моя проект за връзка тук. Всеки, който може да ми помогне с това, е високо оценен. Мисля, че Ин съм на края на силите си с това.


person msrameshp    schedule 16.08.2014    source източник


Отговори (2)


marcoseu е прав, грешката There is no timestamp for... означава, че кармата не може да намери файла, но има още.

Бих препоръчал да направите основния път на karma вашия корен на проекта. Това избягва Karma да прави пътеките на файловете абсолютни вместо относителни, което прави нещата по-прости и избягва проблеми с референтни пътища (поне на моята операционна система Windows).

Вашият тест трябва да бъде изискващ модул (т.е. използвайки define), така че да може да е сигурен, че обектите, които изисква, са напълно заредени. Вижте примерния тест на http://karma-runner.github.io/0.12/plus/requirejs.html

karma.config.js basePath: "../", files: [ 'test/test-main.js', {pattern: 'test/specs/*.js', included: false}, {pattern: 'www/**/*.js', included: false}, ],

Сега всичките ви файлове се обслужват от Karma под /base.

test-main.js require.config({ baseUrl: "/base/www/scripts",

Отстраняване на грешки

Но най-важното е, че можете да отстраните грешки във всичко това. Стартирайте Karma, превключете към създадения от Karma chrome екземпляр, щракнете върху бутона за отстраняване на грешки, отворете инструментите за разработчици на chrome. Проверете конзолата и вашите изходни файлове. Особено източникът на debug.html, тъй като в долната част има дефиницията на всичките ви обслужвани карма файлове.

Можете също да зададете точки на прекъсване и след това да опресните страницата, за да наблюдавате как се изпълняват тестовете. Ще можете сами да видите защо получавате грешки при теста. Печеля.

person RockResolve    schedule 22.08.2014

Грешката There is no timestamp for... означава, че karma няма достъп до въпросния файл. Трябва да дефинирате директорията www, така че да е достъпна от karma. Опитайте следното:

karma.config.js files: [ 'test-main.js', {pattern: './specs/*.js', included: true}, {pattern: '../../www/**/*.js', included: false} ],

Разгледайте karma.conf в проект angularAMD и документацията на Karma за файлове.

person marcoseu    schedule 18.08.2014
comment
Моделът www изглежда едно ниво твърде дълбок и трябва да бъде {pattern: '../www/**/*.js', included: false}, - person RockResolve; 22.08.2014