未找到单元测试期望 SpyOn
Unit Test Expect SpyOn Not Found
我有一个指令(限制 A)处理事件点击,并根据值调用服务。
指令:
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];
});
测试:
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(function (_$rootScope_, _$compile_, _myFactory_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
var html = '<div><a my-directive value="\'red\'"></a></div>';
myFactory = _myFactory_;
spyOn(myFactory , 'red').and.callThrough();
element = $compile(angular.element(html))(scope);
scope.$digest();
}));
it('should be red and call myFactory.red', function () {
element.click();
expect(myFactory.red).toHaveBeenCalled();
});
通过以上,我得到错误:
Expected spy red to have been called.
我正在使用 Jasmine 2
您单击的是 <div>
,而不是具有指令和事件处理程序的 <a>
。做:
element.find('a').click();
或者简单地从编译的 HTML 中删除 <div>
。
我有一个指令(限制 A)处理事件点击,并根据值调用服务。
指令:
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];
});
测试:
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(function (_$rootScope_, _$compile_, _myFactory_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
var html = '<div><a my-directive value="\'red\'"></a></div>';
myFactory = _myFactory_;
spyOn(myFactory , 'red').and.callThrough();
element = $compile(angular.element(html))(scope);
scope.$digest();
}));
it('should be red and call myFactory.red', function () {
element.click();
expect(myFactory.red).toHaveBeenCalled();
});
通过以上,我得到错误:
Expected spy red to have been called.
我正在使用 Jasmine 2
您单击的是 <div>
,而不是具有指令和事件处理程序的 <a>
。做:
element.find('a').click();
或者简单地从编译的 HTML 中删除 <div>
。