diff --git a/packages/netlify-cms-media-library-cloudinary/src/__tests__/index.spec.js b/packages/netlify-cms-media-library-cloudinary/src/__tests__/index.spec.js index d8bdda95..f9a3afe8 100644 --- a/packages/netlify-cms-media-library-cloudinary/src/__tests__/index.spec.js +++ b/packages/netlify-cms-media-library-cloudinary/src/__tests__/index.spec.js @@ -29,15 +29,9 @@ describe('cloudinary media library', () => { }; /** - * Every time the integration is initialized, a script tag is dynamically - * generated and added to the page. The initialization is on hold until - * the `load` event is broadcast, but that doesn't happen during testing, - * so we wait for the script tag to be added to the dom and then manually - * call its `onreadystatechange` method, which resolves the promise and - * allows initialization to continue. - * - * This also ensures that the script is being added to the DOM, and in a way - * that is not tied to script loading implementation details. + * We load the Cloudinary library by injecting a script tag to the page + * head. Initialization waits for the script to load, so here we fake it. + * This also tests that the expected script is added to the DOM. */ waitForElement(() => { const url = 'https://media-library.cloudinary.com/global/all.js'; @@ -252,7 +246,7 @@ Object { expect(mediaLibrary.show).toHaveBeenCalledWith(showOptions); }); - it('enforces multiple: false if allowMultiple is true', async () => { + it('enforces multiple: false if allowMultiple is false', async () => { const options = { config: { multiple: true, diff --git a/packages/netlify-cms-media-library-uploadcare/src/__tests__/index.spec.js b/packages/netlify-cms-media-library-uploadcare/src/__tests__/index.spec.js new file mode 100644 index 00000000..0d2b19f4 --- /dev/null +++ b/packages/netlify-cms-media-library-uploadcare/src/__tests__/index.spec.js @@ -0,0 +1,219 @@ +import { queryHelpers, waitForElement } from 'dom-testing-library'; +import uuid from 'uuid/v4'; +import uploadcare from '../index'; + +function generateMockUrl({ count = 1, cdnUrl } = {}) { + const baseUrl = 'https://ucarecdn.com'; + const url = `${baseUrl}/${uuid()}~${count}/`; + const result = + count === 1 ? `${url}nth/0/` : Array.from({ length: count }, (val, idx) => `${url}nth/${idx}/`); + if (cdnUrl) { + return { result, cdnUrl: url }; + } + return result; +} + +describe('uploadcare media library', () => { + let handleInsert; + let simulateCloseDialog; + let uploadcareScripts = []; + const TEST_PUBLIC_KEY = 123; + const defaultConfig = { + imagesOnly: false, + multiple: false, + previewStep: true, + }; + + beforeEach(() => { + /** + * We load the Uploadcare library by injecting script tags to the page + * head. Initialization waits for the scripts to load, so here we fake it. + * This also tests that the expected scripts are added to the DOM. + */ + [/uploadcare\.full\.js$/, /uploadcare\.tab-effects\.js$/].forEach(pattern => { + waitForElement(() => { + return queryHelpers.queryByAttribute('src', document, pattern); + }).then(script => { + uploadcareScripts.push(script); + script.onreadystatechange(); + }); + }); + + let openDialogCallback; + + /** + * Mock of the uploadcare widget object itself. + */ + window.uploadcare = { + registerTab: jest.fn(), + openDialog: jest.fn(() => ({ + done: jest.fn(cb => { + openDialogCallback = cb; + }), + })), + fileFrom: jest.fn((type, url) => + Promise.resolve({ + testFileUrl: url, + }), + ), + loadFileGroup: () => ({ + done: cb => cb(), + }), + }; + + /** + * Mock to manually call the close dialog registered callback. + */ + simulateCloseDialog = result => + openDialogCallback({ + promise: () => Promise.resolve(result), + }); + + /** + * Spy to serve as the Netlify CMS insertion handler. + */ + handleInsert = jest.fn(); + }); + + afterEach(() => { + /** + * Remove the script elements from the dom after each test. + */ + const { head } = document; + uploadcareScripts.forEach(script => head.contains(script) && head.removeChild(script)); + uploadcareScripts = []; + }); + + it('exports an object with expected properties', () => { + expect(uploadcare).toMatchInlineSnapshot(` +Object { + "init": [Function], + "name": "uploadcare", +} +`); + }); + + describe('initialization', () => { + it('sets global required configuration', async () => { + const options = { + config: { + publicKey: TEST_PUBLIC_KEY, + }, + }; + await uploadcare.init({ options }); + expect(window.UPLOADCARE_LIVE).toEqual(false); + expect(window.UPLOADCARE_MANUAL_START).toEqual(true); + expect(window.UPLOADCARE_PUBLIC_KEY).toEqual(TEST_PUBLIC_KEY); + }); + + it('registers the effects tab', async () => { + const mockEffectsTab = { mockEffectsTab: true }; + window.uploadcareTabEffects = mockEffectsTab; + await uploadcare.init(); + expect(window.uploadcare.registerTab).toHaveBeenCalledWith('preview', mockEffectsTab); + }); + }); + + describe('configuration', () => { + const options = { + config: { + foo: 'bar', + }, + }; + + it('has defaults', async () => { + const integration = await uploadcare.init(); + await integration.show(); + expect(window.uploadcare.openDialog).toHaveBeenCalledWith(null, defaultConfig); + }); + + it('can be defined globally', async () => { + const expectedConfig = { + ...defaultConfig, + ...options.config, + }; + const integration = await uploadcare.init({ options }); + await integration.show(); + expect(window.uploadcare.openDialog).toHaveBeenCalledWith(null, expectedConfig); + }); + + it('can be defined per field', async () => { + const expectedConfig = { + ...defaultConfig, + ...options.config, + }; + const integration = await uploadcare.init(); + await integration.show({ config: options.config }); + expect(window.uploadcare.openDialog).toHaveBeenCalledWith(null, expectedConfig); + }); + }); + + describe('show method', () => { + const options = { + config: { + foo: 'bar', + }, + }; + + it('accepts imagesOnly as standalone property', async () => { + const expectedConfig = { + ...defaultConfig, + ...options.config, + imagesOnly: true, + }; + const integration = await uploadcare.init(); + await integration.show({ config: options.config, imagesOnly: true }); + expect(window.uploadcare.openDialog).toHaveBeenCalledWith(null, expectedConfig); + }); + + it('allows multiple selection if allowMultiple is not false', async () => { + options.config.multiple = true; + const expectedConfig = { + ...defaultConfig, + ...options.config, + multiple: true, + }; + const integration = await uploadcare.init({ options }); + await integration.show({ config: options.config }); + expect(window.uploadcare.openDialog).toHaveBeenCalledWith(null, expectedConfig); + }); + + it('disallows multiple selection if allowMultiple is false', async () => { + options.config.multiple = true; + const expectedConfig = { + ...defaultConfig, + ...options.config, + multiple: false, + }; + const integration = await uploadcare.init({ options }); + await integration.show({ config: options.config, allowMultiple: false }); + expect(window.uploadcare.openDialog).toHaveBeenCalledWith(null, expectedConfig); + }); + + it('passes selected image url to handleInsert', async () => { + const url = generateMockUrl(); + const mockResult = { cdnUrl: url }; + const integration = await uploadcare.init({ handleInsert }); + await integration.show(); + await simulateCloseDialog(mockResult); + expect(handleInsert).toHaveBeenCalledWith(url); + }); + + it('passes multiple selected image urls to handleInsert', async () => { + options.config.multiple = true; + const { result, cdnUrl } = generateMockUrl({ count: 3, cdnUrl: true }); + const mockDialogCloseResult = { cdnUrl, count: 3 }; + const integration = await uploadcare.init({ options, handleInsert }); + await integration.show(); + await simulateCloseDialog(mockDialogCloseResult); + expect(handleInsert).toHaveBeenCalledWith(result); + }); + }); + + describe('enableStandalone method', () => { + it('returns false', async () => { + const integration = await uploadcare.init(); + expect(integration.enableStandalone()).toEqual(false); + }); + }); +}); diff --git a/packages/netlify-cms-media-library-uploadcare/src/index.js b/packages/netlify-cms-media-library-uploadcare/src/index.js index ca5890f4..7be26884 100644 --- a/packages/netlify-cms-media-library-uploadcare/src/index.js +++ b/packages/netlify-cms-media-library-uploadcare/src/index.js @@ -1,6 +1,8 @@ import { loadScript } from 'netlify-cms-lib-util'; import { Iterable } from 'immutable'; +const CDN_BASE_URL = 'https://ucarecdn.com'; + /** * Default Uploadcare widget configuration, can be overriden via config.yml. */ @@ -44,12 +46,12 @@ function getFileGroup(files) { * promises, or Uploadcare groups when possible. Output is wrapped in a promise * because the value we're returning may be a promise that we created. */ -function getFiles(value, cdnBase) { +function getFiles(value) { if (Array.isArray(value) || Iterable.isIterable(value)) { const arr = Array.isArray(value) ? value : value.toJS(); - return isFileGroup(arr) ? getFileGroup(arr) : arr.map(val => getFile(val, cdnBase)); + return isFileGroup(arr) ? getFileGroup(arr) : Promise.all(arr.map(val => getFile(val))); } - return value && typeof value === 'string' ? getFile(value, cdnBase) : null; + return value && typeof value === 'string' ? getFile(value) : null; } /** @@ -57,10 +59,9 @@ function getFiles(value, cdnBase) { * object. Group urls that get passed here were not a part of a complete and * untouched group, so they'll be uploaded as new images (only way to do it). */ -function getFile(url, cdnBase) { +function getFile(url) { const groupPattern = /~\d+\/nth\/\d+\//; - const baseUrls = ['https://ucarecdn.com', cdnBase].filter(v => v); - const uploaded = baseUrls.some(baseUrl => url.startsWith(baseUrl) && !groupPattern.test(url)); + const uploaded = url.startsWith(CDN_BASE_URL) && !groupPattern.test(url); return window.uploadcare.fileFrom(uploaded ? 'uploaded' : 'url', url); } @@ -85,7 +86,7 @@ function openDialog(files, config, handleInsert) { * Initialization function will only run once, returns an API object for Netlify * CMS to call methods on. */ -async function init({ options = { config: {} }, handleInsert }) { +async function init({ options = { config: {} }, handleInsert } = {}) { const { publicKey, ...globalConfig } = options.config; const baseConfig = { ...defaultConfig, ...globalConfig }; @@ -113,7 +114,7 @@ async function init({ options = { config: {} }, handleInsert }) { * On show, create a new widget, cache it in the widgets object, and open. * No hide method is provided because the widget doesn't provide it. */ - show: ({ value, config: instanceConfig = {}, allowMultiple, imagesOnly }) => { + show: ({ value, config: instanceConfig = {}, allowMultiple, imagesOnly = false } = {}) => { const config = { ...baseConfig, imagesOnly, ...instanceConfig }; const multiple = allowMultiple === false ? false : !!config.multiple; const resolvedConfig = { ...config, multiple }; @@ -124,9 +125,9 @@ async function init({ options = { config: {} }, handleInsert }) { * from the Uploadcare library will have a `state` method. */ if (files && !files.state) { - files.then(result => openDialog(result, resolvedConfig, handleInsert)); + return files.then(result => openDialog(result, resolvedConfig, handleInsert)); } else { - openDialog(files, resolvedConfig, handleInsert); + return openDialog(files, resolvedConfig, handleInsert); } },