Muestra las diferencias entre dos versiones de la página.
| Ambos lados, revisión anterior Revisión previa Próxima revisión | Revisión previa | ||
|
wiki2:nodejs:patterns [2017/05/11 20:48] alfred |
wiki2:nodejs:patterns [2020/05/09 09:25] (actual) |
||
|---|---|---|---|
| Línea 88: | Línea 88: | ||
| }); | }); | ||
| </code> | </code> | ||
| + | |||
| + | Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, into a dependent object. | ||
| + | |||
| + | Dependency injection is really helpful when it comes to testing. You can easily mock your modules' dependencies using this pattern. | ||
| + | <code> | ||
| + | var db = require('db'); | ||
| + | // do some init here, or connect | ||
| + | db.init(); | ||
| + | |||
| + | var userModel = require('User')({ | ||
| + | db: db | ||
| + | }); | ||
| + | |||
| + | userModel.create(function (err, user) { | ||
| + | | ||
| + | }); | ||
| + | </code> | ||
| + | <code> | ||
| + | var test = require('tape'); | ||
| + | var userModel = require('User'); | ||
| + | |||
| + | test('it creates a user with id', function (t) { | ||
| + | var user = { | ||
| + | id: 1 | ||
| + | }; | ||
| + | var fakeDb = { | ||
| + | query: function (done) { | ||
| + | done(null, user); | ||
| + | } | ||
| + | } | ||
| + | | ||
| + | userModel({ | ||
| + | db: fakeDb | ||
| + | }).create(function (err, user) { | ||
| + | t.equal(user.id, 1, 'User id should match'); | ||
| + | t.end(); | ||
| + | }) | ||
| + | | ||
| + | }); | ||
| + | </code> | ||
| + | <code> | ||
| + | function userModel (options) { | ||
| + | var db; | ||
| + | | ||
| + | if (!options.db) { | ||
| + | throw new Error('Options.db is required'); | ||
| + | } | ||
| + | | ||
| + | db = options.db; | ||
| + | | ||
| + | return { | ||
| + | create: function (done) { | ||
| + | db.query('INSERT ...', done); | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | |||
| + | module.exports = userModel; | ||
| + | </code> | ||
| + | In the example above we have two different dbs. In the index.js file we have the "real" db module, while in the second we simply create a fake one. This way we made it really easy to inject fake dependencies into the modules we want to test. | ||
| + | |||
| ===== Middleware / Pipeline ===== | ===== Middleware / Pipeline ===== | ||
| Línea 135: | Línea 196: | ||
| </code> | </code> | ||
| - | code> | + | <code> |
| // app.js | // app.js | ||
| require('./foo.js'); | require('./foo.js'); | ||