Analysis on the problems and solutions of using dependency injection in Node.js

Source: Internet
Author: User
Tags require

This article mainly introduces the problems and solutions of using dependency injection in Node.js, Node.js is a framework to run JavaScript application on server-side, and the friends who need it can refer to

Recently, I have shifted to using dependency injection to help understand the simple ways of separating code and helping to test. However, the modules in Node.js rely on the system APIs provided by Node, which makes it difficult to tell if private dependencies are properly used. General dependency injection is difficult to use in this case, but don't give up hope now.

Requirecauses problem

Node.js can easily import dependencies according to requirements. It works well and is simpler than the AMD mode loader such as Requirejs. The problem comes when we simulate those dependencies. If the loading of the model in the Node.js is controlled, what can we do to control the use of the pseudo object during the test? We can use node's VM model, and we can load the model in a new context with the VM. Running in the new context, we can control how the demand reflects the model.


Thanks for this article, you can now offer a pretty good solution. The code is below:


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The "> var VM = require (' VM '); var fs =" Require (' FS '); var path = require (' path ');  /** * Helper for unit Testing: *–load module with mocked dependencies *–allow accessing private state of the MO Dule * * @param {string} filePath absolute path to module (file to load) * @param {object=} mocks Hash of mocked Dependenc IES */exports.loadmodule = function (FilePath, mocks) {mocks = mocks | | {};  //This are necessary to allow relative path modules within loaded file//i.e. requiring./some inside File/a/b.js Needs to is resolved to/a/some var resolvemodule = function (module) {if (Module.charat (0)!== '. ') return module; retur N Path.resolve (Path.dirname (FilePath), module); };   var exports = {}; var context = {Require:function (name) {return Mocks[name] | | require(Resolvemodule (name)); }, Console:console, Exports:exports, module: {exports:exports}};   Vm.runinnewcontext (Fs.readfilesync (FilePath), context); return context; };

You can also download code snippets here. Although it is not the most published code in the article, he can still use some explanations. When we test, we have to load this module into the test and use theloadmodulefunction instead of Ofrequire to load the module test.

The first parameter filepath specifies the lookup location where we want to test the model. The second parameter mocks contains an object, and the object's property name matches the name of the model we are trying to require. The values specified by those attributes are pseudo objects and are used in place of a model that is generally require.

Essentially, the VM is used to load and run the model in another "context". In other words, we have rebuilt global variables (such as require and exports) so that we can control them. Note that we have written a new require function that is available. All you do is check to see if there is a mock dependency on the name of the execution, and if you have it every day, I'll delegate it to that common require function.

Example of using the module loader

If you're still a bit confused, you can look at the code example below to see how it's used in context, perhaps to help you understand something. First, we create a simple module.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24-25 var fs = require (' FS '); Module.exports = {//do something with ' FS '} Imagine this is cool, right?   Anyway, now we're testing that module, but we're going to simulate FS to see how it's used internally. Jasmine ' s Syntax (' Somemodule ', function () {var loadModule = require (' Module-loader '). LoadModule;   var module, Fsmock;   Beforeeach (function () {Fsmock = {//a mock for ' FS '}; Load the module with mock FS instead of real FS module = LoadModule ('./web-server.js ', {fs:fsmock});   }); It (' should work ', function () {//a test that utilizes the fact so we can now control ' FS '}); });

The main note is that from 7 to 12 lines, we created a pseudo object for FS and used our new LoadModule function to connect this object to the small module above (I mean awesome! Remember, this is awesome, right?).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.