Angular.js + Karma + Jasmine:未知的服务提供商

时间:2015-06-23 23:06:57

标签: javascript angularjs karma-jasmine

我正在为以下Angular.js服务编写测试:

var module = angular.module('wp', [ 'aws', 'lodash', 'jquery', 'moment', 'wp.model' ]);

/**
 * Wordpress service.
 */
module.service('wpService', function(_, $http, $q, $aws, Post) {
    var self = this;

    /**
     * HTTP request.
     */
    this.http = function(config) {
        var $config = _.clone(config);

        if ($config.user && $config.password) {
            $config.headers = $config.headers || {};
            $config.headers.Authorization = 'Basic ' + btoa($config.user + ':' + $config.password);
        }

        return $http($config);
    };

    // ..
}

测试用例如下:

/**
 * Unit tests for wpService.
 */
describe('apService', function() {

    var wpService;

    beforeEach(angular.module('wp'));

    beforeEach(inject(function(_wpService_) {
        wpService = _wpService_;
    }));

    it('is defined', function() {
        expect(wpService).toBeDefined();
    });
});

这看起来像是教科书一样。不幸的是,我收到了以下错误:

Chrome 43.0.2357 (Mac OS X 10.10.3) apService is defined FAILED
TypeError: queueableFn.fn.call is not a function
Error: [$injector:unpr] Unknown provider: wpServiceProvider <- wpService
http://errors.angularjs.org/1.4.1/$injector/unpr?p0=wpServiceProvider%20%3C-%20wpService
    at /Users/jdolan/Coding/tuuli-syndicate/bower_components/angular/angular.js:68:12

我的karma.config.js包含模块以及angular-mocks.js

// list of files / patterns to load in the browser
    files : [ 'bower_components/jquery/dist/jquery.js',
              'bower_components/lodash/lodash.js',
              'bower_components/moment/moment.js',
              'bower_components/x2js/xml2json.js',
              'bower_components/aws-sdk/dist/aws-sdk.js',
              'bower_components/angular/angular.js',
              'bower_components/angular-route/angular-route.js',
              'bower_components/angular-mocks/angular-mocks.js',
              'app/**/*.js',
              'tests/**/*.js' ],

我使用的是Angular 1.4.1,Karma 0.12.36。

1 个答案:

答案 0 :(得分:11)

仔细阅读the angular-mocks example here

angular.module()函数返回实际的角度模块,而module()angular.mock.module()的缩写。在代码中替换此行,您应该全部设置:

beforeEach(module('wp'));