Catch-22 recursive Node modules bloat when using Mocha

I worked on a project that uses some custom Node.js modules. I created a helper module that helps with loading some helper methods:

/helpers/index.js:

var mutability = require('./mutability'),
    cb = require('./cb'),
    build = require('./build'),
    userAgent = require('./userAgent'),
    is = require('./is'),
    query = require('./query'),
    config = require('./config'),
    _ = require('underscore')

module.exports = _.extend({
    cb: cb,
    build: build,
    userAgent: userAgent,
    is: is,
    query: query,
    config: config
}, mutability)

For entertainment mutability.js:

'use strict'

module.exports = {
    setReadOnly: function(obj, key) {
        // whatever
        return obj
    },
    setWritable: function(obj, key) {
        // whatever
        return obj
    }
}

One of my modules buildrequires the class to do some type checking:

/helpers/build.js

'use strict'

var urljoin = require('url-join'),
    config = require('./config'),
    cb = require('./cb'),
    Entity = require('../lib/entity'),
    _ = require('underscore')

module.exports = {
    url: function(options) {
        return urljoin(
            config.baseUrl,
            options.client.orgId,
            options.client.appId,
            options.type, (typeof options.uuidOrName === 'string') ? options.uuidOrName : ""
        )
    },
    GET: function(options) {
        options.type = options.type || args[0] instanceof Entity ? args[0]._type : args[0]
        options.query = options.query || args[0] instanceof Entity ? args[0] : undefined
        return options
    }
}

And Entitythen you need helpers:

/lib/entity.js

'use strict'

var helpers = require('../helpers'),
    ok = require('objectkit'),
    _ = require('underscore')

var Entity = function(object) {
    var self = this

    _.extend(self, object)

    helpers.setReadOnly(self, ['uuid'])

    return self
}

module.exports = Entity

For some reason, when I run this using Mocha, I get helpersin quality {}and Mocha throws:

Uncaught TypeError: helpers.setReadOnly is not a function

When I run /lib/entity.jsdirectly with node, it prints the appropriate module. What gives? Why does mocha explode?

0
1

, index.js entity.js.

( ), require:

/helpers/index.js -> /helpers/build.js -> /lib/entity.js -> /helpers/index.js

required Node module.exports .

, , , , module.exports = ...; ( JavaScript ).

, : /lib/entity.js /helpers/index.js, index.js module.exports = _.extend(...).

, , , /lib/entity.js, , :

// Extend `module.exports` instead of replacing it with a new object.
module.exports = _.extend(
    module.exports,
    {
        cb: cb,
        build: build,
        userAgent: userAgent,
        is: is,
        query: query,
        config: config
    },
    mutability
);

, , , .

+1

Source: https://habr.com/ru/post/1622796/


All Articles