From 35ed9558154cd016b9e983dd9cd76539db349c40 Mon Sep 17 00:00:00 2001 From: Iku-turso Date: Thu, 17 Nov 2022 13:41:38 +0200 Subject: [PATCH] fix: Make auto-register work in already built packages --- .../src/autoRegister.js | 4 ++-- .../src/autoRegister.test.js | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/packages/injectable/extension-for-auto-registration/src/autoRegister.js b/packages/injectable/extension-for-auto-registration/src/autoRegister.js index 5a34c62c..d69618b4 100644 --- a/packages/injectable/extension-for-auto-registration/src/autoRegister.js +++ b/packages/injectable/extension-for-auto-registration/src/autoRegister.js @@ -1,4 +1,4 @@ -import { flatMap, forEach, tap } from 'lodash/fp'; +import { flatMap, forEach, tap, set } from 'lodash/fp'; import { pipeline } from '@ogre-tools/fp'; import { isInjectable } from '@ogre-tools/injectable'; import requireContextFake from './requireContextFake'; @@ -34,7 +34,7 @@ const verifyInjectables = ([[fileName, module]]) => { export default ({ fs, path }) => ({ di, targetModule, getRequireContexts }) => { - if (!targetModule.require.context) { + if (targetModule.require && !targetModule.require.context) { targetModule.require.context = requireContextFake({ targetModule: targetModule, fs, diff --git a/packages/injectable/extension-for-auto-registration/src/autoRegister.test.js b/packages/injectable/extension-for-auto-registration/src/autoRegister.test.js index 9c42f1a2..6ff73aa7 100644 --- a/packages/injectable/extension-for-auto-registration/src/autoRegister.test.js +++ b/packages/injectable/extension-for-auto-registration/src/autoRegister.test.js @@ -203,6 +203,30 @@ describe('autoRegister', () => { expect(actual).toBe('some-instance'); }); + it('given operating in already built package, injects', () => { + const injectableStub = getInjectable({ + id: 'some-injectable', + instantiate: () => 'some-instance', + }); + + const di = createContainer('some-container'); + + autoRegister({ + di, + // Note: require being undefined in module implies package being already built. + targetModule: { require: undefined, path: '/some-module-path' }, + + getRequireContexts: () => [ + // Note: in packages that are already built, require contexts are inlined. + getRequireContextStub({ default: injectableStub }), + ], + }); + + const actual = di.inject(injectableStub); + + expect(actual).toBe('some-instance'); + }); + it('given injectable file with no injectables, when auto-registering, throws', () => { const requireContextStub = Object.assign( () => ({