2016-09-29 1 views
1

Я пробовал разные варианты, основываясь на информации, которая там есть, но пока не дошла до рабочего решения.Угловая инъекция впрыска 1.x в модульных тестах

Я пытаюсь ввести службу в единичный тест для тестирования.

Моя текущая реализация ниже. Проблема в том, что услуга не такова: ReferenceError: Can't find variable: SerializationService - Я пробовал использовать inject() в preeach тоже безрезультатно.

spec.js

'use strict'; 

describe('SerializationService', function() { 

    var SerializationService; 

    beforeEach(function() { 

    module('app'); 

    inject(function (_SerializationService_) { 
     SerializationService = _SerializationService_; 
    }); 
    }); 

    it('should have a SerializationService', function() { 
    expect(SerializationService).toBeDefined(); 
    }); 
}); 

Другие вещи, которые я пробовал:

  • Использование отдельного модуля включает в себя между приложением и модулем инъекционные услуг в другом Еогеасп с помощью подчеркивания обозначения

karma.conf

// Karma configuration 
// http://karma-runner.github.io/0.12/config/configuration-file.html 
// Generated on 2016-08-15 using 
// generator-karma 0.8.3 

module.exports = function (config) { 
    'use strict'; 

    config.set({ 
    // enable/disable watching file and executing tests whenever any file changes 
    autoWatch: true, 

    // base path, that will be used to resolve files and exclude 
    basePath: '../../', 

    // testing framework to use (jasmine/mocha/qunit/...) 
    frameworks: ['jasmine'], 

    // list of files/patterns to load in the browser 
    files: [ 
     'bower_components/angular/angular.js', 
     'bower_components/angular-mocks/angular-mocks.js', 
     'bower_components/angular-animate/angular-animate.js', 
     'bower_components/angular-cookies/angular-cookies.js', 
     'bower_components/angular-resource/angular-resource.js', 
     'bower_components/angular-route/angular-route.js', 
     'bower_components/angular-sanitize/angular-sanitize.js', 
     'bower_components/angular-touch/angular-touch.js', 
     'bower_components/json3/lib/json3.js', 
     'bower_components/es5-shim/es5-shim.js', 
     'bower_components/jquery/dist/jquery.js', 
     'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js', 
     'bower_components/angular-resource/angular-resource.js', 
     'bower_components/angular-cookies/angular-cookies.js', 
     'bower_components/angular-sanitize/angular-sanitize.js', 
     'bower_components/angular-animate/angular-animate.js', 
     'bower_components/angular-touch/angular-touch.js', 
     'bower_components/angular-route/angular-route.js', 
     'bower_components/angular-ui-router/release/angular-ui-router.js', 
     'bower_components/angular-audio/app/angular.audio.js', 
     'bower_components/socket.io.client/dist/socket.io-1.3.5.js', 
     'bower_components/angular-socket-io/socket.js', 
     'bower_components/angular-local-storage/dist/angular-local-storage.js', 
     'bower_components/moment/moment.js', 
     'bower_components/angular-moment/angular-moment.js', 
     'bower_components/angular-scroll-glue/src/scrollglue.js', 
     'bower_components/angular-gravatar/build/angular-gravatar.js', 
     'bower_components/angular-socialshare/dist/angular-socialshare.min.js', 
     'bower_components/clipboard/dist/clipboard.js', 
     'bower_components/ngclipboard/dist/ngclipboard.js', 
     'bower_components/color-thief/src/color-thief.js', 
     'bower_components/ngColorThief/angular-colorthief.js', 
     'bower_components/hashids/dist/hashids.js', 
     'bower_components/ngEmbed/src/ng-embed.js', 
     'bower_components/angular-bootstrap/ui-bootstrap-tpls.js', 
     'bower_components/ngEmbed/src/ng-embed.js', 
     'app/scripts/**/*.js', 
     'test/unit/mock/**/*.js', 
     'test/unit/spec/**/*.js' 
    ], 

    // list of files/patterns to exclude 
    exclude: [], 

    // web server port 
    port: 8081, 

    // Start these browsers, currently available: 
    // - Chrome 
    // - ChromeCanary 
    // - Firefox 
    // - Opera 
    // - Safari (only Mac) 
    // - PhantomJS 
    // - IE (only Windows) 
    browsers: [ 
     'PhantomJS' 
    ], 

    // Which plugins to enable 
    plugins: [ 
     'karma-phantomjs-launcher', 
     'karma-jasmine' 
    ], 

    // Continuous Integration mode 
    // if true, it capture browsers, run tests and exit 
    singleRun: false, 

    colors: true, 

    // level of logging 
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG 
    logLevel: config.LOG_INFO 

    //// Uncomment the following lines if you are using grunt's server to run the tests 
    // proxies: { 
    // '/': 'http://localhost:9000/' 
    // }, 
    // //URL root prevent conflicts with the site root 
    // urlRoot: '_karma_' 
    }); 
}; 

ответ

0

Проблема была в моих Mocking модулей

Я использовал метод клеть вместо Командлет Get:

Это неправильно:

angular 
    .module('meow-mock', []) 
    .factory('somemock', function() { 
    //code 
    }); 

Это право:

angular 
    .module('meow-mock') 
    .factory('somemock', function() { 
    //code 
    }); 
1

Я создал небольшой образец на plunker: Plunker example

Он использует угловой издевается и жасмин для тестирования. Основная часть:

describe('TestService', function(){ 
    beforeEach(module('test')); 

    var TestService; 
    beforeEach(inject(function(_TestService_) { 
    TestService = _TestService_; 
    })); 

    it('returns 42', function(){ 
    expect(TestService.testMethod()).toEqual(42); 
    }); 
}); 

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

+0

Привет, чувак, спасибо за ваш ответ. Я пробовал реализовать это, но получаю 'Ошибка: [$ injector: unpr] Неизвестный поставщик: SerializationServiceProvider <- SerializationService" все еще кажется проблемой. Мне интересно, связано ли это с «karma.conf»? Для справки я вставил его в исходный вопрос. Спасибо :) –

+0

Не могли бы вы обновить свое сообщение, чтобы включить свой тестовый код? (т. е. файл с 'описанием') – nagyf

+0

, обновленный с последними спецификациями –

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