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

别说谁变了你拦得住时间么 提交于 2019-12-24 04:23:11

问题


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"?


回答1:


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.



来源:https://stackoverflow.com/questions/30289882/how-can-i-mock-ui-routers-resolve-values-when-testing-a-states-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!