diff --git a/src/EmailEditor.tsx b/src/EmailEditor.tsx index 52316273e..7bb64591c 100644 --- a/src/EmailEditor.tsx +++ b/src/EmailEditor.tsx @@ -3,6 +3,7 @@ import React, { useState, useImperativeHandle, useMemo, + useRef, } from 'react'; import type { DisplayMode, UnlayerEditor } from '@unlayer/types'; @@ -51,9 +52,14 @@ function EmailEditorInner { return () => { - editor?.destroy(); + editorRef.current?.destroy(); }; }, []); @@ -93,7 +99,7 @@ function EmailEditorInner ({ + loadScript: (callback: Function) => callback(), +})); + +it('destroys the editor on unmount', () => { + const destroy = jest.fn(); + (global as any).unlayer = { + createEditor: jest.fn(() => ({ + destroy, + addEventListener: jest.fn(), + removeEventListener: jest.fn(), + })), + }; + + const { unmount } = render(); + unmount(); + + expect(destroy).toHaveBeenCalledTimes(1); +}); diff --git a/test/quickUnmount.test.tsx b/test/quickUnmount.test.tsx new file mode 100644 index 000000000..7615c929f --- /dev/null +++ b/test/quickUnmount.test.tsx @@ -0,0 +1,25 @@ +import React from 'react'; +import { render, act } from '@testing-library/react'; +import Editor from '../src'; + +let scriptLoadedCallback: Function; +jest.mock('../src/loadScript', () => ({ + loadScript: (callback: Function) => { + scriptLoadedCallback = callback; + }, +})); + +it('does not create the editor when unmounted before the embed script loads', () => { + const createEditor = jest.fn(); + (global as any).unlayer = { createEditor }; + + const { unmount } = render(); + unmount(); + + // Embed script finishes loading after the component is gone. + act(() => { + scriptLoadedCallback(); + }); + + expect(createEditor).not.toHaveBeenCalled(); +});