2015-05-17 22 views
2

我在寫一個使用ui-router的角度應用程序,我正在爲我的ui-router配置編寫測試。如何在測試狀態配置時模擬ui-router的解析值?

具體而言,我期待測試綁定到狀態的我的onEnteronExit回調。這些回調依賴於在狀態上定義的解析。我如何模擬onEnteronExit函數中使用的解析?

例如,說我有一個狀態定義如下:

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

在上面的茉莉測試例子,我將如何讓這個在我onEnter擁有的"Sally Sallington"值所使用的currentUser

回答

4

您可以像使用其他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() { 
    // ... 
    }); 
}); 

您甚至可以引用可以從每個單獨測試更改的變量。

相關問題