簡體   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