1

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

1 Answer 1

0

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);
    });
});
Sign up to request clarification or add additional context in comments.

6 Comments

The problem is the appState method is called as the module is created, sorry I should have mentioned the appState method is in another project which the project I'm testing is added to at runtime. So I need to provide a mock as soon as the module is created otherwise it'll cause an error ' Error: [$injector:modulerr] Failed to instantiate module someModule due to: TypeError: $stateProvider.appState is not a function'
@OrangeJuice1- Could you try this alternative pattern
Unfortunately if I use the other pattern I still get the same error
@OrangeJuice1- try now, I changed it to $state
No neither seem to work you just get the same error that appState is undefined. From debugging the test, the stateProviderMock isn't even passed to the module when it's created, it just uses the original $stateProvider.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.