Skip to content

Commit

Permalink
Fix uncaught DOMException error
Browse files Browse the repository at this point in the history
  • Loading branch information
sdb1228 committed Feb 18, 2020
1 parent 4721a51 commit ff8b2d4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/view/use-announcer/use-announcer.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ export default function useAnnouncer(contextId: ContextId): Announce {
// unmounting after a timeout to let any announcements
// during a mount be published
setTimeout(function remove() {
// not clearing the ref as it might have been set by a new effect
getBodyElement().removeChild(el);

// checking if element exists before remove to prevent errors
if (getBodyElement().contains(el)) {
// not clearing the ref as it might have been set by a new effect
getBodyElement().removeChild(el);
}
// if el was the current ref - clear it so that
// we can get a warning if announce is called
if (el === ref.current) {
Expand Down
18 changes: 18 additions & 0 deletions test/unit/view/announcer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,24 @@ it('should remove the element when unmounting after a timeout', () => {
expect(getElement('5')).not.toBeTruthy();
});

it('should not remove the element when unmounting after a timeout if the element does not exist', () => {
const { unmount } = render(
<WithAnnouncer contextId="5">{getMock()}</WithAnnouncer>,
);

const doc = new DOMParser().parseFromString(
'<!doctype html><title>wat</title>',
'text/html',
);
document.write(doc);
unmount();
expect(() => jest.runOnlyPendingTimers()).not.toThrow(
new DOMException(
"Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.",
),
);
});

it('should set the text content of the announcement element', () => {
// arrange
const mock = getMock();
Expand Down

0 comments on commit ff8b2d4

Please sign in to comment.