问题描述
我正在使用 ui-router 编写一个 angular 应用程序,我正在为我的 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!");
}
}
});
在本例中,我想测试 嘿,你不是鲍勃!"
消息功能.
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();
});
});
在上面的 jasmine 测试示例中,我将如何使 currentUser
在我的 onEnter
中使用的值为 "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 的解析值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!