如何在Jasmine单元测试中监视window.onclick



我怎样才能监视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,我该如何模拟事件?

测试中有几个问题。

  1. 您不触发click事件,但安装另一个(无效( 单击window上的事件处理程序classController.window.onclick(elementInpt)
  2. classController.setClass()您在(据说(触发click事件。因此,事件处理程序将未准备就绪 时间。
  3. 您不需要spywindow.onclick因为expect检查所做的最终更改 在 HTML 元素上。

下面您将看到要在测试中进行的相关更改。

it('should add class active to the wrapper', () => {
...
// spyOn(classController.window, 'onclick'); // not needed
classController.setClass();
elementInpt.click();
...
});

另请注意,windowdocument是全球可用的,不必在ClassController课程的constructor中提供。

最新更新