cus*_*ice 1 unit-testing jasmine angularjs
我有一个使用的基本控制器$stateParams.
angular.module('example')
.controller('SampleCtrl', ['$stateParams',
function($stateParams) {
var vm = this;
vm.isSomething = ($stateParams.isSomething === 'true') ? true : false;
}
]);
Run Code Online (Sandbox Code Playgroud)
在我的单元测试中,我需要$stateParams.isSomething在一次测试中将其设置为true,在另一次测试中将其设置为false.
describe('SampleCtrl Test', function() {
var ctrl, scope, $stateParams;
// set default stateParams
$stateParams = { isSomething: 'false' };
beforeEach(function(){
inject(function($rootScope, $controller){
scope = $rootScope.$new();
ctrl = $controller('SampleCtrl', {
$scope: scope,
$stateParams: $stateParams
});
});
});
describe('when isSomething is false', function() {
it('should be false', function() {
expect(ctrl.isSomething).toBe(false);
});
});
describe('when isSomething is true', function() {
beforeEach(function() {
$stateParams.isSomething = 'true';
});
it('should be true', function() {
// THIS IS FAILING
expect(ctrl.isSomething).toBe(true);
});
});
});
Run Code Online (Sandbox Code Playgroud)
如何正确模拟$stateParams不同测试的不同状态?
我认为您需要使用更新的范围对象再次实例化控制器.
您也有一些命名问题,请参阅下面代码中的注释.
describe('SampleCtrl Test', function() {
var ctrl, scope, $stateParams, $controller;
// set default stateParams
// you have called it 'something' in your controller not 'isSomething'
$stateParams = { something: 'false' };
beforeEach(function(){
// load module
module('example');
inject(function($rootScope, _$controller_){
scope = $rootScope.$new();
// angular removes the _'s for you so you can call it $controller
$controller = _$controller_;
ctrl = $controller('SampleCtrl', {
$scope: scope,
$stateParams: $stateParams
});
});
});
describe('when isSomething is false', function() {
it('should be false', function() {
expect(ctrl.isSomething).toBe(false);
});
});
describe('when isSomething is true', function() {
beforeEach(function() {
// you have called it 'something' in your controller not 'isSomething'
$stateParams.something = 'true';
// instantiate a new controller with the updated $stateParams object
ctrl = $controller('SampleCtrl', {
$scope: scope,
$stateParams: $stateParams
});
});
it('should be true', function() {
// THIS IS FAILING
expect(ctrl.isSomething).toBe(true);
});
});
});
Run Code Online (Sandbox Code Playgroud)