使用 $state.transitionTo 的单元测试控制器 [英] Unit testing controller which uses $state.transitionTo
问题描述
在控制器中,我有一个函数,它使用 $state.transitionTo
来重定向"到另一个状态.
within a controller i have a function which uses $state.transitionTo
to "redirect" to another state.
现在我被困在测试这个功能,我总是得到错误错误:没有这样的状态'state-two'
.我该如何测试?我很清楚控制器对其他状态一无所知,但是我如何模拟这种状态?
now i am stuck in testing this function, i get always the error Error: No such state 'state-two'
. how can i test this? it its totally clear to me that the controller does not know anything about the other states, but how can i mock this state?
一些代码:
angular.module( 'mymodule.state-one', [
'ui.state'
])
.config(function config($stateProvider) {
$stateProvider.state('state-one', {
url: '/state-one',
views: {
'main': {
controller: 'MyCtrl',
templateUrl: 'mytemplate.tpl.html'
}
}
});
})
.controller('MyCtrl',
function ($scope, $state) {
$scope.testVar = false;
$scope.myFunc = function () {
$scope.testVar = true;
$state.transitionTo('state-two');
};
}
);
<小时>
describe('- mymodule.state-one', function () {
var MyCtrl, scope
beforeEach(module('mymodule.state-one'));
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
MyCtrl = $controller('MyCtrl', {
$scope: scope
});
}));
describe('- myFunc function', function () {
it('- should be a function', function () {
expect(typeof scope.myFunc).toBe('function');
});
it('- should test scope.testVar to true', function () {
scope.myFunc();
expect(scope.testVar).toBe(true);
expect(scope.testVar).not.toBe(false);
});
});
});
推荐答案
免责声明:我自己没有做过这个,所以我完全不知道它是否会起作用,以及你想要的是什么.
Disclaimer: I haven't done this myself, so I totally don't know if it will work and is what your are after.
从我的头顶,我想到了两个解决方案.
From the top of my head, two solutions come to my mind.
1.) 在您的测试中预先配置 $stateProvider
以返回 state-two
的模拟状态 这也是 ui-router 项目本身要测试的内容状态转换.
1.) In your tests pre configure the $stateProvider
to return a mocked state for the state-two
That's also what the ui-router project itself does to test state transitions.
2.) 捕获并解析异常并将其解释为已完成的测试,如果尝试到达 state-two
2.) catch and parse the exception and interpret it as fulfilled test if tries to get to state-two
第二种方法看起来很黑,所以我会投第一种.
The second approach seems very hackish, so I would vote for the first.
但是,很有可能我完全误会了你,应该好好休息一下.
However, chances are that I totally got you wrong and should probably get some rest.
beforeEach(module(function ($stateProvider) {
$stateProvider.state('state-two', { url: '/' });
}));
这篇关于使用 $state.transitionTo 的单元测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!