我怎样才能监视Jasmine中的window.onclick事件。 尝试为窗口单击创建一个间谍并调用它,但这不起作用。
我想用茉莉花覆盖的代码:
setClass() {
const input = this.document[0].querySelector('.wrapper');
const inputButton = this.document[0].querySelector('.input-button');
const inputField = this.document[0].querySelector('.input-field');
this.window.onclick = function(event) {
if (event.target !== inputButton && input.classList.contains('active')) {
input.classList.remove('active');
} if (event.target === inputField) {
input.classList.add('active');
} else {
input.classList.remove('active');
}
};
}
这是我尝试过的:
describe('setClass method', () => {
it('should add class active to the wrapper', () => {
const classController = new classController(this.document, this.window);
const elementWrapper = angular.element('<div class="wrapper"></div>');
const elementBtn = angular.element('<button class="input-button"></button>');
const elementInpt = angular.element('<input class="input-field" type="text">');
spyOn(classController.document[0], 'querySelector').and.returnValues(elementWrapper[0], elementBtn[0], elementInpt[0]);
spyOn(classController.window, 'onclick');
classController.window.onclick(elementInpt);
classController.setClass();
expect(elementWrapper[0].outerHTML).toBe('<div class="wrapper active"></div>');
});
});
代码现在被覆盖到this.window.onclick,我该如何模拟事件?
测试中有几个问题。
- 您不触发
click
事件,但安装另一个(无效( 单击window
上的事件处理程序classController.window.onclick(elementInpt)
classController.setClass()
您在(据说(触发click
事件。因此,事件处理程序将未准备就绪 时间。- 您不需要
spy
window.onclick
因为expect
检查所做的最终更改 在 HTML 元素上。
下面您将看到要在测试中进行的相关更改。
it('should add class active to the wrapper', () => {
...
// spyOn(classController.window, 'onclick'); // not needed
classController.setClass();
elementInpt.click();
...
});
另请注意,window
和document
是全球可用的,不必在ClassController
课程的constructor
中提供。