【问题标题】:How can I mock ui-router's resolve values when testing a state's configuration?测试状态配置时如何模拟 ui-router 的解析值?
【发布时间】:2015-05-17 17:32:18
【问题描述】:

我正在使用 ui-router 编写一个 Angular 应用程序,并希望为我的 ui-router 配置编写测试。

具体来说,我希望测试绑定到状态的 onEnter 和 onExit 回调。这些回调依赖于在状态上定义的解析。如何模拟 onEnter 和 onExit 函数中使用的解析?

例如,假设我有一个如下定义的状态:

// 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!");
        }
    }
});

在本例中,我想测试"hey, you aren't bob!" 消息功能。

对于初学者,我会这样写:

// 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();
    });
});

在上面的 jasmine 测试示例中,我将如何使 onEnter 中使用的 currentUser 的值为 "Sally Sallington"?

【问题讨论】:

    标签: angularjs unit-testing jasmine angular-ui-router


    【解决方案1】:

    您可以像其他 Angular 值/服务一样模拟已解析的值。我使用类似的东西:

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

    您甚至可以引用一个可以从每个单独的测试中更改的变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2015-09-27
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多