如何使用Jasmine / karma正确注入工厂并进行测试?

时间:2016-02-19 01:22:44

标签: angularjs jasmine karma-jasmine

这是我的工厂/ base.js

angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .config(['$locationProvider', function($locationProvider){
        $locationProvider.html5Mode(true);
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {

这是我的test_base.js

describe('Factory: BaseService', function() {
    var fctry, mockBackend;

    beforeEach(function() {

        module('BaseApp');

        inject(function($factory, $httpBackend) {
            mockBackend = $httpBackend;
            fctry = $factory('BaseService', {});
        });
    });

    it('logout() should POST to /logout', function() {
        // I want to test if the logout(cb) function posts to /logout and, on success, redirect to '/'
        // but on failure, calls accessErrors and the cb.
    });
});

这是我的业力配置文件:

files: [
  '../angular.js',
  'node_modules/angular-mocks/angular-mocks.js',

  '../base.js',

  'tests/test_base.js',
],

当我执行karma start并运行测试时,我收到此错误/失败:

Chromium 48.0.2564 (Ubuntu 0.0.0) Factory: BaseService logout() should POST to /logout FAILED
    Error: [$injector:unpr] Unknown provider: $factoryProvider <- $factory
    http://errors.angularjs.org/1.3.15/$injector/unpr?p0=%24factoryProvider%20%3C-%20%24factory

...

Chromium 48.0.2564 (Ubuntu 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.053 secChromium 48.0.2564 (Ubuntu 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.114 secs / 0.053 secs)

为什么它已经失败了,怎么说$factoryProvider是一个未知的提供者呢?

1 个答案:

答案 0 :(得分:2)

它认为您正在尝试注入工厂,这是一个功能,而不是提供商,因此无法工作。

您还错过了underscore trick

尝试更改此内容:

var fctry, mockBackend;
beforeEach(function() {

    module('BaseApp');

    inject(function($factory, $httpBackend) {
        mockBackend = $httpBackend;
        fctry = $factory('BaseService', {});
    });
});

对此:

var BaseService, $httpBackend;
beforeEach(function() {

    module('BaseApp');

    inject(function(_BaseService_, _$httpBackend_) {
        $httpBackend = _$httpBackend_;
        BaseService = _BaseService_;
    });
});