From 80e320fd83781f81d028d5c67f6dd8c614be7546 Mon Sep 17 00:00:00 2001 From: Hannah Wolfe Date: Wed, 25 Mar 2020 11:19:16 +0000 Subject: [PATCH] Cleanup repeated module mocking utils - mock non existant module util was defined twice - split it out properly from the rest of the utils, update all references - this allows us to move this util out of the codebase along with other code, e.g. the image manipulation code --- ghost/image-transform/test/transform.test.js | 8 +++---- ghost/image-transform/test/utils/modules.js | 23 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 ghost/image-transform/test/utils/modules.js diff --git a/ghost/image-transform/test/transform.test.js b/ghost/image-transform/test/transform.test.js index f6e1ec3a8f..8a3062f978 100644 --- a/ghost/image-transform/test/transform.test.js +++ b/ghost/image-transform/test/transform.test.js @@ -3,12 +3,12 @@ const sinon = require('sinon'); const fs = require('fs-extra'); const errors = require('@tryghost/errors'); const manipulator = require('../../../../server/lib/image/manipulator'); -const testUtils = require('../../../utils'); +const mockUtils = require('../../../utils/mocks'); describe('lib/image: manipulator', function () { afterEach(function () { sinon.restore(); - testUtils.unmockNotExistingModule(); + mockUtils.modules.unmockNonExistentModule(); }); describe('canTransformFileExtension', function () { @@ -55,7 +55,7 @@ describe('lib/image: manipulator', function () { return sharpInstance; }); - testUtils.mockNotExistingModule('sharp', sharp); + mockUtils.modules.mockNonExistentModule('sharp', sharp); }); it('resize image', function () { @@ -118,7 +118,7 @@ describe('lib/image: manipulator', function () { describe('installation', function () { beforeEach(function () { - testUtils.mockNotExistingModule('sharp', new Error(), true); + mockUtils.modules.mockNonExistentModule('sharp', new Error(), true); }); it('sharp was not installed', function () { diff --git a/ghost/image-transform/test/utils/modules.js b/ghost/image-transform/test/utils/modules.js new file mode 100644 index 0000000000..ff1295fa37 --- /dev/null +++ b/ghost/image-transform/test/utils/modules.js @@ -0,0 +1,23 @@ +const Module = require('module'); +const originalRequireFn = Module.prototype.require; + +/** + * helper fn to mock non-existent modules + * mocks.modules.mockNonExistentModule(/pattern/, mockedModule) + */ +exports.mockNonExistentModule = (modulePath, module, error = false) => { + Module.prototype.require = function (path) { + if (path.match(modulePath)) { + if (error) { + throw module; + } + return module; + } + + return originalRequireFn.apply(this, arguments); + }; +}; + +exports.unmockNonExistentModule = () => { + Module.prototype.require = originalRequireFn; +};