Ошибка при получении 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 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. И мой модульный тест:

         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... означает, что карма не может найти файл, но это еще не все.

Я бы рекомендовал сделать базовый путь кармы корнем вашего проекта. Это позволяет избежать кармы, делающей пути к файлам абсолютными, а не относительными, что упрощает работу и позволяет избежать проблем со ссылками на пути (по крайней мере, в моей ОС Windows).

Ваш тест должен быть модулем require (т. е. с использованием определения), чтобы он мог быть уверен, что требуемые объекты полностью загружены. См. пример теста по адресу 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, переключитесь на экземпляр Chrome, созданный Karma, нажмите кнопку отладки, откройте инструменты разработчика Chrome. Проверьте консоль и ваши исходные файлы. Особенно источник debug.html, так как в его нижней части есть определение всех ваших файлов кармы.

Вы также можете установить точки останова, а затем обновить страницу, чтобы посмотреть, как выполняются тесты. Вы сможете сами увидеть, почему вы получаете ошибки теста. Победить.

person RockResolve    schedule 22.08.2014

Ошибка There is no timestamp for... означает, что karma не может получить доступ к рассматриваемому файлу. Вам нужно определить каталог www, чтобы он был доступен по карме. Попробуйте следующее:

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 выглядит на один уровень глубже и должен быть {шаблон: '../www/**/*.js', включая: false}, - person RockResolve; 22.08.2014