英文:
How to write test case for if else with htmlelement in karma jasmine test case?
问题
The code you want to cover in your unit test is:
if (targetElement.className === 'fa fa-question-circle-o' || targetElement.className === 'info-icon') {
return false;
}
You can proceed with your unit test as follows:
it('should return false for specific classname', () => {
// Create a mock target element with the desired class name
const targetElement = document.createElement('div');
targetElement.className = 'fa fa-question-circle-o';
// Dispatch a click event with the mock target element
const clickEvent = new MouseEvent('click', {
bubbles: true,
cancelable: true,
target: targetElement,
});
document.dispatchEvent(clickEvent);
// Call the onClick method and capture its return value
const result = component.onClick(clickEvent, targetElement);
// Expect the result to be false
expect(result).toBe(false);
});
This test creates a mock target element with the class name 'fa fa-question-circle-o', dispatches a click event with this element as the target, and then calls the onClick
method. Finally, it asserts that the return value of the method is false
, as expected.
英文:
**Component code:**
@HostListener('document:click', ['$event', '$event.target'])
onClick(event: MouseEvent, targetElement: HTMLElement): void| boolean {
try {
this.shareService.addBreadCrumb('Host listener other than helpbox...');
if (targetElement.className === 'fa fa-question-circle-o' || targetElement.className === 'info-icon') {
return false;
}
this.isHelpboxVisible = null;
} catch (e) {
Sentry.captureException(e);
}
}
I want to code cover the following part:
if (targetElement.className === 'fa fa-question-circle-o' || targetElement.className === 'info-icon') {
return false;
}
Please suggest how can I proceed. What I have tried ( I am new to unit testing):
it('should return false for specific classname', () => {
document.dispatchEvent(new MouseEvent('click'));
fixture.debugElement.query(By.css('.fa fa-question-circle-o.info-icon'));
const result = component.onClick(new MouseEvent('click'), 'test' as any);
expect(result).toBe(false);
});
答案1
得分: 1
"只需模拟 HTML 元素如下所示:"
it('对于特定的类名,应返回 false', () => {
const result = component.onClick(new MouseEvent('click'), { className: 'fa fa-question-circle-o' } as any);
expect(result).toBe(false);
});
英文:
Just mock the html element like so:
it('should return false for specific classname', () => {
const result = component.onClick(new MouseEvent('click'), { className: 'fa fa-question-circle-o' } as any);
expect(result).toBe(false);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论