AngularJS:如何对提供商进行单元测试

时间:2014-04-18 16:03:21

标签: javascript angularjs unit-testing

经过几个小时的搜索和实验,我的思绪被打破了。关于如何对AngularJS提供商进行单元测试的直接和有效的例子是无处可寻的,无论我怎么努力,我都无法让自己工作。

在下面的示例中,服务已正确注入并正常工作。提供程序未注入且无法配置,因为它永远不会到达可能配置的代码块中。

是否有人可以提供工作'如何对AngularJS提供商进行单元测试'例子?

angular.module('app',[]);
angular.module('app').service('testBasicService', function () {
    return {
        serviceMethod: function () {
            alert("serviceMethod");
        }
    };
});

angular.module('app').provider('testAdvancedService', function () {
    this.$get = function () {
        this.providerMethod = function () {
            alert("providerMethod");
        }
    }
});


describe("Test", function () {
    beforeEach(module("app"), function (testAdvancedServiceProvider) {
        // code never arrives here
    });

    it("should just work", inject(function (testBasicService,     testAdvancedService) {
        testBasicService.serviceMethod();
        testAdvancedService.providerMethod(); // testAdvancedService is undefined here
    }));
});

1 个答案:

答案 0 :(得分:1)

我认为testAdvancedService在测试中未定义的原因是因为提供程序中的$ get方法没有返回值。如果确实返回了一个对象,那么该对象将是测试中注入的testAdvancedService。

如果您在提供商中定义了要测试的功能,我发现这有效:

describe("Test", function () {

    beforeEach(module("app"));

    var provider;
    beforeEach(function () {
        module(function ($provide, testAdvancedServiceProvider) {
            provider = $provide.provider('testAdvancedServiceProvider', testAdvancedServiceProvider);
        });
    });

    it("should just work", inject(function (testBasicService, testAdvancedService) {
        testBasicService.serviceMethod();
        alert(testAdvancedService); // result of the $get function. undefined as it is now.
        provider.providerMethod();
    }));
});
相关问题