Spyon provider during configuration phase in angular.js application

I am writing unit tests for an Angular.js application (with karma and jasmine) and I want to test for specific behavior in the CONFIG phase of a module. I would like to confirm that a certain PROVIDER function is being called. I thought I could do this with a spy using the provider method, but getting access to the provider before the "wait" turned out to be quite complicated. Here is a sample code:

Module code (tested)

var myApp = angular.module('myApp', ['restangular']);
myApp.config(['RestangularProvider', function (RestangularProvider) {
    RestangularProvider.setBaseUrl('http://someurl:someport/');
}]);

I tried various solutions to get a link to RestangularProvider and apply a spy to it, and all failed. Closest I could get the code below:

Unit Test Code

describe("Test if setBaseUrl was called", function () {
    var RestangularProvider;
    beforeEach(module('myApp', function(_RestangularProvider_) {
        RestangularProvider = _RestangularProvider_;
        spyOn(RestangularProvider, "setBaseUrl").and.callThrough();
    }));

    it("should call setBaseUrl.", function() {
        expect(RestangularProvider.setBaseUrl).toHaveBeenCalled();
    });
});

I really get a link to the RestangularProvider, but before that, the "config" function of the module is called, so I think the spy is not getting the settings.

, "" "" . Restangular.configuration.baseUrl , setBaseUrl, , .

Angular.js, " ", , , , :]

, ?

+4
2

, , , , , "beforeEach". , , " ".

describe("Test if setBaseUrl was called", function () {
    var RestangularProvider;
    //Setup the spy.
    beforeEach(function () {

      module("restangular", function(_RestangularProvider_) {
        RestangularProvider = _RestangularProvider_;
        spyOn(_RestangularProvider_, 'setBaseUrl').and.callThrough();
      });
    });

    beforeEach(module('myApp'));

    it("should call setBaseUrl.", function() {
        expect(RestangularProvider.setBaseUrl).toHaveBeenCalled();
    });
});
+4

, , .
beforeEach. inject() ( ) beforeEach.

describe('Test if setBaseUrl was called', function () {
  var RestangularProvider;
  //Setup the spy.
  beforeEach(function () {

    module('restangular', function(_RestangularProvider_) {
      RestangularProvider = _RestangularProvider_;
      spyOn(_RestangularProvider_, 'setBaseUrl').and.callThrough();
    });

    module('myApp');

    inject();
  });

  it('should call setBaseUrl.', function() {
    expect(RestangularProvider.setBaseUrl).toHaveBeenCalled();
  });
});

: http://java.dzone.com/articles/unit-testing-config-and-run

0

Source: https://habr.com/ru/post/1546745/


All Articles