codysehl
codysehl

Reputation: 1595

How can I mock ui-router's resolve values when testing a state's configuration?

I'm writing an angular application using ui-router and I'm looking to write tests for my ui-router configuration.

Specifically, I'm looking to test my onEnter and onExit callbacks bound to a state. These callbacks rely on resolves which are defined on the state. How can I mock out the resolves being used in the onEnter and onExit functions?

For example, say I have a state defined as follows:

// bobConfig.js
.state('bob', {
    url: '/bob',
    templateUrl: "bob.html",
    controller: "bobController",
    resolve: {
        currentUser: function() {
            return "Bob Bobbertson";
        }
    },
    onEnter: function(currentUser) {
        if(currentUser == "Bob Bobbertson") {
            console.log("hello bob!");
        } else {
            console.log("hey, you aren't bob!");
        }
    }
});

In this example, I'd like to test the "hey, you aren't bob!" message functionality.

For starters, I'd write something like this:

// productsConfig.spec.js
describe("Products state config", function(){
    it("should tell everyone but bob that they aren't bob", function() {
        // set up currentUser to return "Sally Sallington"
        expectYouArentBobMessageToBePrinted();
    });
});

In the above jasmine test example, how would I make it so that the currentUser being used in my onEnter has a value of "Sally Sallington"?

Upvotes: 2

Views: 2464

Answers (1)

OrganicPanda
OrganicPanda

Reputation: 2677

You can mock resolved values in the same way as other Angular values/services. I use something like:

describe('Products state config', function() {
  beforeEach(function() {
    module('whatever.module', function($provide) {
      $provide.service('currentUser', function() {
        return 'Some User';
      });
    });
  });

  it('should do something ...', function() {
    // ...
  });
});

You could even refer to a variable that you can change from each individual test.

Upvotes: 4

Related Questions