我正在关注 AngularJS 文档上的迁移练习 for input[checkbox]
,它说要更改
it('should update the model', inject(function($compile, $rootScope) {
var inputElm = $compile('<input type="checkbox" ng-model="checkbox" />')($rootScope);
inputElm[0].click(); // Or different trigger mechanisms, such as jQuery.trigger()
expect($rootScope.checkbox).toBe(true);
});
进入这个:
it('should update the model', inject(function($compile, $rootScope, $rootElement, $document) {
var inputElm = $compile('<input type="checkbox" ng-model="checkbox" />')($rootScope);
$rootElement.append(inputElm);
$document.append($rootElement);
inputElm[0].click(); // Or different trigger mechanisms, such as jQuery.trigger()
expect($rootScope.checkbox).toBe(true);
});
我的设置与第一次不同,但我尽量遵循它。
我的设置的近似值是这样的:
import { getInjector, getDirective, toBeChecked, clickOn } from './test-helper.js';
describe('testing a click', () => {
let $rootElement = false;
let $document = false;
beforeEach( () => {
const $injector = getInjector();
$rootElement = $injector.get('$rootElement');
$document = $injector.get('$document');
});
it('should click the input', () =>{
const $directive = getDirective('directive-with-checkbox');
const $checkbox = directive.find('input#uniq-id-of-checkbox');
clickOn($checkbox, $rootElement, $document);
expect($checkbox).toBeChecked()
})
});
和clickOn
功能:
export function clickOn($element, $rootElement, $document){
const mouseClickEvent = document.createEvent('MouseEvent');
if($element.prop('type') === 'checkbox' && $rootElement && $document) {
$rootElement.append($element);
$document.append($rootElement); //<--- breaks
}
mouseClickEvent.init('click');
$element[0].dispatchEvent(mouseClickEvent);
}
我的期望是将点击事件转移到触发复选框的更改。
我的完整错误信息是:
TypeError: null is not an object (evaluating 'context.createDocumentFragment') in filename.js
我无法弄清楚我的代码与示例有何不同,以使其无法按预期工作。
这似乎与为什么 $(document).append() 在 jQuery 1.9.1 中不起作用有关?但我很困惑为什么官方文档建议这样做document.append(...
。
当我将它从更改$document
为document.body
($document
有一个主体但 jquery 似乎没有找到?)时,我可以让业力浏览器调试器通过那里,但不是我正在运行的 PhantomJS 实例。
我如何真正获得点击来切换我的复选框?