繁体   English   中英

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

[英]AngularJS : How to unit-test a provider

经过几个小时的搜索和试验,我的想法震惊了。 找不到如何对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
    }));
});

我认为在测试中未定义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();
    }));
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM