1
我有一個指令屬性,傳遞價值,並基於價值的行動:單元測試指令Click事件基於範圍值
define(function() {
'use strict';
var myDirective = function ($rootScope, myFactory) {
return {
restrict: 'A',
scope: {
_myValue : '=value'
},
link: function(scope, element, attrs) {
element.bind('click', function() {
if (scope._myValue === 'red') {
myFactory.red();
}
if (scope._myValue === 'green') {
myFactory.green();
}
if (scope._myValue === 'black') {
myFactory.black();
}
});
}
};
};
return ['$rootScope', 'myFactory', myDirective];
});
HTML:
<a my-directive value="\'red\'"></a>
單元測試:
define(['angular-mocks'], function() {
'use strict';
var angular = require('angular');
describe('<-- Directive Spec ------>', function() {
var scope, $compile, element;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(['$rootScope', '$compile', function (_$rootScope_, _$compile_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
var html = '<a my-directive value="\'red\'"></a>';
element = $compile(angular.element(html))(scope);
scope.$digest();
}]));
it('should be red and call myFactory.red', function() {
element.click();
});
UPDATE:
define(['angular-mocks'], function() {
'use strict';
var angular = require('angular');
describe('<-- Directive Spec ------>', function() {
var scope, $compile, element, myFactory;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(['$rootScope', '$compile', function (_$rootScope_, _$compile_, _myFactory_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
var html = '<a my-directive value="\'red\'"></a>';
myFactory = _myFactory_;
spyOn(myFactory , 'red');
element = $compile(angular.element(html))(scope);
scope.$digest();
}]));
it('should be red and call myFactory.red', function() {
expect(myFactory.red).toHaveBeenCalled();
});
試過以上,並得到錯誤:
Error: spyOn could not find an object to spy upon for red()
廠例子:
define(['require', 'angular'], function (require, angular) {
'use strict';
var myFactory = function() {
return {
red: function() {
console.log('red');
},
green: function() {
console.log('green');
},
black: function() {
console.log('black');
}
};
};
return myFactory;
});
謝謝,很好的解決方案。我必須定義myFactory嗎?間諜是否在消化之前?後? –
聲明一個'myFactory' var就像你用'scope'做的一樣。然後,注入'_myFactory_'並將其影響到'myFactory' var:'var myFactory = _myFactory_'。而已。然後,儘快將間諜(編譯前) – Zakaria
謝謝,試過了,看看上面的更新,看到一個錯誤 –