UNPKG

@commercetools-frontend/sdk

Version:
54 lines (47 loc) 2.42 kB
import _JSON$stringify from '@babel/runtime-corejs3/core-js-stable/json/stringify'; import _Array$isArray from '@babel/runtime-corejs3/core-js-stable/array/is-array'; import _findIndexInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/find-index'; import _concatInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/concat'; import _spliceInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/splice'; import _Promise from '@babel/runtime-corejs3/core-js-stable/promise'; import { deepEqual } from 'fast-equals'; import { v4 } from 'uuid'; /** * START --> * Remove once `@commercetools/sdk-client` exposes proper types. */ /* <-- END */ const serialize = data => { const undefinedPlaceholder = v4(); const placeholderRegexp = new RegExp("\"".concat(undefinedPlaceholder, "\""), 'g'); const mapUndefinedValues = (_k, v) => v === undefined ? undefinedPlaceholder : v; const withPlaceholders = _JSON$stringify(data, mapUndefinedValues, 2); return withPlaceholders.replace(placeholderRegexp, 'undefined'); }; const throwIfNoMocksArePassed = mocks => { if (!mocks || !_Array$isArray(mocks) || mocks.length === 0) { throw new Error('Missing or invalid argument for `mocks`. Expected an array of mocked actions.'); } }; const isSdkAction = action => action.type === 'SDK'; const isSdkMockSuccess = mock => mock.response !== undefined; const createTestMiddleware = mocks => { throwIfNoMocksArePassed(mocks); // We clone the mocks so we can keep the user-provided mocks around for // the debugging message. The mocksStack gets mutated, while mocks // should never be mutated. const mocksStack = [...mocks]; return () => next => action => { var _context; if (!isSdkAction(action)) { return next(action); } const index = _findIndexInstanceProperty(mocksStack).call(mocksStack, item => deepEqual(item.action, action)); if (index === -1) throw new Error(_concatInstanceProperty(_context = "Could not find any more mocks for action ".concat(serialize(action), " in ")).call(_context, serialize(mocks))); const mock = mocksStack[index]; // Mocks should only be used once, so we remove it from the stack. _spliceInstanceProperty(mocksStack).call(mocksStack, index, 1); return isSdkMockSuccess(mock) ? _Promise.resolve(mock.response) : _Promise.reject(mock.error); }; }; export { createTestMiddleware };