OrangeJuice1-
OrangeJuice1-

Reputation: 109

How to mock AngularJS module config providers

In our module we have a custom method defined that essentially adds on more functionality to $stateProvider...

    (function () {
      'use strict';
    
      angular
        .module('someModule', [])
        .config(config);
    
    
    
      config.$inject = ['$stateProvider'];
      function config ($stateProvider) {

  $stateProvider
      .appState({})

The problem is no matter what I try in my spec file, I cannot override the appState method, the original method just gets used.

 beforeEach(function () {
    angular.mock.module('someModule', function ($stateProvider) {
        spyOn($stateProvider, 'appState').and.returnValue({
            stateName: 'mockState',
            url: '/mock-url'
        });
    });
});

So how do you mock a config provider such as $stateProvider from ui-router?

It's worth mentioning the appState method is in another project that this project is added to at runtime, so I need to be able to mock appState straight away on module creation otherwise it results in error...

 Error: [$injector:modulerr] Failed to instantiate module someModule due to:
TypeError: $stateProvider.appState is not a function

Upvotes: 1

Views: 29

Answers (1)

Naren Murali
Naren Murali

Reputation: 57986

You could use the $provide and mock the values before you serve them using $provide.

  const stateProviderMock = {
      appState: () => {}
  };

  beforeEach(module(function($provide) {
    spyOn(stateProviderMock, 'appState').and.returnValue({});
    $provide.provider('$state', function() {
      return stateProviderMock;
    });
  }));

  beforeEach(module('someModule'));

Or you can try this pattern:

beforeEach(function(){
    module('someModule');
    module(function ($provide) {
        $provide.value('$state', stateProviderMock);
    });
});

Upvotes: 0

Related Questions