在业力茉莉花中注入自定义服务

时间:2017-08-24 11:26:17

标签: angularjs unit-testing jasmine karma-jasmine

  

我正在尝试茉莉与业力。我有自定义服务   我需要在我的spec文件中注入的ApiService。但是当我努力的时候   注入ApiService我得到错误:[$ injector:unpr]未知   provider:ApiService< - ApiService

     

这是我的控制器

'use strict';
angular.module('assessmentApp')
    .controller('NewUserController', NewUserController)
    .run(["$rootScope", "$anchorScroll", function($rootScope, $anchorScroll) {
        $rootScope.$on("$locationChangeSuccess", function() {
            $anchorScroll();
        });
    }]);

NewUserController.$inject = ['$scope', '$rootScope', '$location', '$timeout', 'ApiService'];

function NewUserController($scope, $rootScope, $location, $timeout, ApiService) {
    //console.log("innn   NewUserController2   ::::")
    var vm = this;
    var boardsClassSubjectCombinations = [];
    var studentId = $rootScope.globals.studentId;
    var assessmentCampaignId = $scope.assessmentCampaignId = $rootScope.globals.assessmentCampaignId;
    vm.currentQuestion = 1;

    //sanity check if the user already has academics added
    ApiService.getAll('students/' + studentId + '/latest-student-academic', true, ['students/{{id}}/academic'])
        .then(function(res) {
            if (res.data) {
                //send this guy to home page
                $location.url('/home');
            }
        });

    function getStates() {
        ApiService.getAll('states', true).then(function(response) {
            $scope.states = response.data;
        });
    }
    getStates();

}
  

这是我的测试文件

describe('NewUserController Test', function() {
  beforeEach(module('assessmentApp'));
    // beforeEach(module('assets'));
    //beforeEach(module('ApiService'))


  var scope, location, timeout,apiService, q, authenticationService;

  beforeEach(inject(function($location,$rootScope,$timeout, ApiService){

    scope = $rootScope.$new();
    location = $location;

    timeout = $timeout;
    q = _$q_;
    console.log(ApiService)

    //spyOn(ApiService, 'ApiService');
    //spyOn(Point, 'method');

    // console.log("ApiService :::"+ApiService)

    //$controller = _$controller_('NewUserController', { $scope: $scope });
    //console.log("NewUserController======="+$controller)
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      console.log("$location ::::"+location)
      console.log("scope ::::"+scope)
      console.log("timeout ::::"+timeout)
      console.log("ApiService ::::"+ApiSrvce)
      console.log("q ::::"+q)
      //console.lopg("authenticationService :::"+authenticationService)
      //console.log("$scope ::::::"+$scope)
      expect(true).toEqual(true);
    });
  });
});
  

这是我的karma.conf.js文件

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: [
      //'test-main.js',
      '../bower_components/jquery/dist/jquery.js',
      '../bower_components/angular/angular.js',
      '../bower_components/bootstrap/dist/js/bootstrap.js',
      '../bower_components/angular-route/angular-route.js',
      '../bower_components/particles.js/particles.js',
      '../bower_components/angular-cookies/angular-cookies.js',
      '../bower_components/toastr/toastr.js',
      '../bower_components/angular-sanitize/angular-sanitize.js',
      '../bower_components/d3/d3.js',
      '../bower_components/c3/c3.js',
      '../bower_components/moment/moment.js',
      '../bower_components/humanize-duration/humanize-duration.js',
      '../bower_components/angular-timer/dist/angular-timer.js',
      '../bower_components/underscore/underscore.js',
      '../bower_components/scrollreveal/dist/scrollreveal.js',
      '../bower_components/lodash/lodash.js',
      '../bower_components/angular-youtube-mb/src/angular-youtube-embed.js',
      '../bower_components/angular-mocks/angular-mocks.js',
      //'../assets/**/*.js',
      //'../assets/**/*.html',
      //'../bower_components/angular/angular.js',
      //'../bower_components/angular-mocks/angular-mocks.js',
      '../app/scripts/app.js',
      '../app/scripts/controllers/**/*.js',
      '../app/scripts/directives/**/*.js',
      '../app/scripts/services/**/*.js',
      '../app/scripts/**/*.js',
      '../../assets/src/assets/services/*.js',
      'spec/**/*.js'      

    ],


    // 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: ['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
  })
}

我看到的是,当我尝试注入任何自定义服务时,它会跳过beforeEach函数,而我获取的日志函数是

LOG: '$location ::::undefined'
LOG: 'scope ::::undefined'
LOG: 'timeout ::::undefined'
LOG: 'ApiService ::::undefined'

1 个答案:

答案 0 :(得分:1)

所以我会建议这种结构:

MaxConcurrentCalls = 1

然后在你的测试中,你会像这样引用apiService。理想情况下,你会为​​你想要测试的每个位创建一个it()语句,比如说,getState()的返回值,但是我们将在这里完成所有这些:

let arr = [{key: "alpha", value: "2"},{key:"beta", value:"3"},{key: "gamma", value: "4"}];
var obj = {};
arr.forEach(item => obj[item.key] = item);
console.log(obj);