Skip to content

Commit

Permalink
fix(getTarget): return array like when allElements parameter is true (#…
Browse files Browse the repository at this point in the history
…1687)

* return array like when allElements parameter in getTarget is true

* Pass a dummy object to test addEventListener

Set ref.current to a dummy object with addEventListener and
removeEventListener.
  • Loading branch information
zachary822 authored and TheSharpieOne committed Oct 28, 2019
1 parent b99e96e commit 0702c45
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/__tests__/TooltipPopoverWrapper.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,7 @@ describe('Tooltip', () => {

it('should not throw when passed a ref object as the target', () => {
const targetObj = React.createRef();
targetObj.current = createSpyObj('div', ['addEventListener', 'removeEventListener']);
const event = createSpyObj('event', ['preventDefault']);
const wrapper = mount(
<TooltipPopoverWrapper target={targetObj}>Yo!</TooltipPopoverWrapper>,
Expand All @@ -373,6 +374,9 @@ describe('Tooltip', () => {
instance.toggle(event);

wrapper.detach();

expect(targetObj.current.addEventListener).toHaveBeenCalled();
expect(targetObj.current.removeEventListener).toHaveBeenCalled();
});

describe('multi target', () => {
Expand Down
9 changes: 9 additions & 0 deletions src/__tests__/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,15 @@ describe('Utils', () => {
document.querySelectorAll.mockRestore();
});

it('should return elements as array like object if allElement param is true', () => {
const data = {};
const spy = jest.fn(() => data);
const elements = Utils.getTarget(spy, true);
expect(elements).toHaveProperty('length');
expect(elements).toContain(data);
expect(spy).toHaveBeenCalled();
});

it('should query the document for the target if the target is a string', () => {
const element = document.createElement('div');
element.className = 'thing';
Expand Down
13 changes: 10 additions & 3 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -301,10 +301,17 @@ export function isArrayOrNodeList(els) {

export function getTarget(target, allElements) {
const els = findDOMElements(target);
if (isArrayOrNodeList(els) && !allElements) {
return els[0];
if (allElements) {
if (isArrayOrNodeList(els)) {
return els;
}
return [els];
} else {
if (isArrayOrNodeList(els)) {
return els[0];
}
return els;
}
return els;
}

export const defaultToggleEvents = ['touchstart', 'click'];
Expand Down

0 comments on commit 0702c45

Please sign in to comment.