Giter Site home page Giter Site logo

weasleyjs's Introduction

WeasleyJS

This is a simple JavaScript dependency registry (or service locator) that serves at least two purposes:

  • Being able to easily swap dependencies programmatically;
  • Making everything easily mockable for testing.

Beware that using a service locator may be an anti-pattern (as opposed to proper dependency injection). That being said, feel free to use this package if it suits your needs and you are okay with the possible drawbacks of this approach.

Setup

npm install --save weasley

or

yarn add weasley

Example

Create a weasley.js module:

import Weasley from 'weasley';

const weasley = new Weasley();

// Register the `awesomeDependency` package under the key `my.awesome.dependency`.
// If `awesomeDependency` has a default export, it will be used.
weasley.register('my.awesome.dependency', () => require('awesomeDependency'));

// Register the `boringExport` named export of the `boringDependency` package under
// the key `my.boring.dependency`.
weasley.register('my.boring.dependency', () => require('boringDependency'), 'boringExport');

// Register all exports (instead of `default`) of `awesomeModule` under the key
// `my.awesome.module`.
weasley.register('my.awesome.module', () => require('./awesomeModule.js'), '*');

export default weasley;

Import your weasley.js module from another module (e.g. awesomeModule.js):

import weasley from './weasley.js';

const awesomeDependency = weasley.container.my.awesome.dependency;
const boringDependency = weasley.container.my.boring.dependency;

export function doThings() {
  awesomeDependency.doSomethingAwesome();
  boringDependency.doSomethingBoring();
}

export default {
  isAwesome: true,
};

In a unit test (example using MochaJS and SinonJS):

import { lazyLoad } from 'weasley';
import weasley from './weasley.js';

// Lazy-load the module to be tested
const awesomeModule = lazyLoad(require.resolve('./awesomeModule.js'), '*');

// Create a mock for a dependency of the module
const myAwesomeMock = {
  doSomethingAwesome: sinon.spy(),
};

describe('awesomeModule', function () {
  before(function () {
    // Override dependency with mock
    weasley.register('my.awesome.dependency', () => myAwesomeMock);
  });

  it('should do something awesome') {
    // ...
  }
});

Lazy-loading vs import/require

When using lazyLoad to import a module, it is not actually imported until it is used for the first time. For instance:

const awesomeModule = lazyLoad(require.resolve('./awesomeModule.js'));
// `./awesomeModule.js` has not been imported yet.

awesomeModule.doSomethingAwesome();
// `./awesomeModule.js` has now been imported.

In unit tests, this behavior allows you to mock dependencies used by the module between the call to lazyLoad and the actual testing of the module.

Also, contrary to using import or require, if you lazy-load the same module at multiple places in your code, you will get different copies of the module.

Be aware that lazy-loading uses the Proxy feature from ES6, which cannot be polyfilled. This means that Proxy must be available in the JavaScript environment that runs your unit tests for lazyLoad to work.

Documentation

Complete documentation is available here.

License

MIT

weasleyjs's People

Contributors

plbrault avatar

Watchers

 avatar

weasleyjs's Issues

Extending lazy-loaded class does not work properly

This test fails on v0.2.0-beta.3:

  it('should be possible to extend a lazy-loaded class', function () {
    const BaseClass = lazyLoad(require.resolve('./testModules/sampleClassModule'));
    class Cls extends BaseClass() {
      constructor(...args) {
        super(...args);
      }
    }
    const inst = new Cls('Nitwit', 'Blubber', 'Oddment', 'Tweak');
    expect(inst.albusQuote).to.be.equal(sampleDependency.speak());
    expect(inst.constructorArgs[0]).to.be.equal('Nitwit');
    expect(inst.constructorArgs[1]).to.be.equal('Blubber');
    expect(inst.constructorArgs[2]).to.be.equal('Oddment');
    expect(inst.constructorArgs[3]).to.be.equal('Tweak');
  });

Dependency is undefined

Problem

When registering dependencies with the same path, the ones declared before are overwritten to undefined.

To reproduce

// weasly.js
import Weasley from 'weasley';

const weasley = new Weasley();
export default weasley;

weasley.register('lib.Logger', () => require('./Logger'));
weasley.register('lib.Settings', () => require('./Settings'));

// Usage
import weasley from './weasley';

const Logger = weasley.container.lib.Logger;
Logger.getLogger(this.constructor.name); // Error cannot call `getLogger` of `undefined`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.