Skip to content

Commit e43afc2

Browse files
johnybDavertMik
authored andcommitted
fix references to support objects when using DI (codeceptjs#1701)
some change to how the support objects are initialized removed the original reference to the support object and replaced it a "cloned" object. However, since Object.assign was used, not all properties have been copied and especially the original reference was lost. This implementation uses a proxy object to load the injected modules on demand and returns the original reference to the module. This should fix all usages of support objects, where the type is not a plain object.
1 parent 7afa9dd commit e43afc2

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

lib/container.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -161,23 +161,23 @@ function createHelpers(config) {
161161
}
162162

163163
function createSupportObjects(config) {
164-
const objects = {};
165-
166-
for (const name in config) {
167-
objects[name] = {}; // placeholders
168-
}
164+
const objects = container.support = new Proxy({}, {
165+
get(target, key) {
166+
// configured but not in support object, yet: load the module
167+
if (key in config && !(key in target)) target[key] = lazyLoad(key);
168+
return target[key];
169+
},
170+
});
169171

170-
if (!objects.I) {
171-
objects.I = require('./actor')();
172+
if (!config.I) {
173+
container.support.I = require('./actor')();
172174

173175
if (container.translation.I !== 'I') {
174-
objects[container.translation.I] = objects.I;
176+
container.support[container.translation.I] = container.support.I;
175177
}
176178
}
177179

178-
container.support = objects;
179-
180-
for (const name in config) {
180+
function lazyLoad(name) {
181181
let newObj = getSupportObject(config, name);
182182
try {
183183
if (typeof newObj === 'function') {
@@ -188,7 +188,7 @@ function createSupportObjects(config) {
188188
} catch (err) {
189189
throw new Error(`Initialization failed for ${name}: ${newObj}\n${err.message}`);
190190
}
191-
Object.assign(objects[name], newObj);
191+
return newObj;
192192
}
193193
const asyncWrapper = function (f) {
194194
return function () {

test/unit/container_test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,16 @@ describe('Container', () => {
121121
assert.ok(container.support('I'));
122122
});
123123

124+
it('should load DI and return a reference to the module', () => {
125+
container.create({
126+
include: {
127+
dummyPage: './data/dummy_page',
128+
},
129+
});
130+
const dummyPage = require('../data/dummy_page');
131+
container.support('dummyPage').should.be.equal(dummyPage);
132+
});
133+
124134
it('should load I from path and execute _init', () => {
125135
container.create({
126136
include: {

0 commit comments

Comments
 (0)