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

Angular.js + Karma + Jasmine: Unknown provider for service

本文关键字:服务 提供商 未知 js+Karma+Jasmine Angular      更新时间:2023-09-26

我正在为以下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。

仔细阅读此处的角度模拟示例。

angular.module()函数返回实际的角度模块,而module()angular.mock.module()的缩写。在你的代码中替换这一行,你应该已经做好了准备:

beforeEach(module('wp'));