我有一个使用服务的自定义指令。当我运行我的单元测试时,我不断收到抛出的错误'库在窗口中不存在'。如何避免在单元测试中出现错误?
示例服务
#student.rb
Class Student < ActiveRecord::Base
has_many :parents
accepts_nested_attributes_for :parents
end
#students_controller.rb
def new
@student = Student.new
@student.parents.build
end
def create
@student = Student.new(student_params)
if @student.save
redirect_to @student
else
render 'new'
end
private
def student_params
params.require(:student).permit(:id, :student_attr_1, :student_attrr_2, parents_attributes: [:id, :father, :mother])
end
#students/new
<%= form_for @student do |f| %>
---student code here ---
<%= f.fields_for :parents do |p| %>
<%= p.label :father, :class => "control-label" %>
<%= p.text_field :father %>
<%= p.label :fmother, :class => "control-label" %>
<%= p.text_field :mother %>
<% end %>
自定义指令
angular.module('example')
.factory('thirdParty', ['$window', function($window) {
if (typeof $window.thirdParty === 'undefined') {
throw new Error('Library does not exist on window');
} else {
return $window.thirdParty;
}
}]);
测试
angular.module('example')
.directive('customDirective', ['thirdParty',
function(thirdParty) {
var defaults, link;
link = function(scope, element, attrs, ctrls) {
// do something with thirdParty
};
return {
restrict: 'A',
require: 'ngModel',
link: link,
};
}]);
答案 0 :(得分:0)
你需要注入$window
(存根也是如此),以及存根/模拟thirdParty
库。
var $window;
beforeEach(function () {
$window = {};
module('yourmodule', function ($provide) {
$provide.value('$window', $window);
});
$window.thirdParty = {};
});
it('throws', function () {
delete $window.thirdParty;
function fn () {
getCompiledElement();
}
expect(fn).to.throw(/does not exist on window/i);
});
it('just works™', function () {
function fn () {
getCompiledElement();
}
expect(fn).to.not.throw;
});