在测试状态配置时,如何模拟ui-router的解析值? [英] How can I mock ui-router's resolve values when testing a state's configuration?
问题描述
我正在使用ui-router编写一个角度应用程序,我正在为我的ui-router配置编写测试。
I'm writing an angular application using ui-router and I'm looking to write tests for my ui-router configuration.
具体来说,我正在寻找测试绑定到状态的 onEnter
和 onExit
回调。这些回调依赖于在状态上定义的结果。如何模拟 onEnter
和 onExit
函数中使用的结果?
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!");
}
}
});
在这个例子中,我想测试嘿,你不是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();
});
});
在上面的茉莉花测试示例中,我如何制作它以便在我的
的值为 onEnter
中使用的currentUser Sally Sallington
?
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"
?
推荐答案
您可以像处理其他Angular值/服务一样模拟已解析的值。我使用类似的东西:
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.
这篇关于在测试状态配置时,如何模拟ui-router的解析值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!