javascript - Dependency Injection and Interfaces in Node -
coming c# background, used interfaces base mock objects off of. created custom mock objects myself , created mock implementation off c# interface.
how do in js or node? create interface can "mock" off of , interface serve real class able implement interface? make sense in js or or node world?
for example in java, same deal, define interface method stubs , use basis create real class or mock class off of.
unfortunately you're not going find standard interface part of javascript. i've never used c#, i've used java, , correct me if i'm wrong, looks you're talking creating interfaces , overriding methods both mock testing purposes, being able implement interfaces in other classes.
because isn't standard javascript feature, i think you'll find there going lot of broad answers here. however, idea of how popular libraries implement this, might suggest looking @ how angularjs looks @ mock testing (there many resources online, google it. starting point, @ how use ngmock
module karma , jasmine.)
also, because of javascript's flexible nature, you'll find can override sort of "class method" (that is, function object member of object, whether new
'ed "class" or plain object) re-implementing wherever need to... there's no special syntax it. understand , how accomplish this, i'd suggest looking ground @ how javascript using prototypal/prototypical inheritance. starting point might considering example this:
function cat(config) { if(typeof config !== 'undefined') { this.meow = config.meow; // config can possibly implement mock methods } } cat.prototype = { this.meow = function() { // meow want use part of "production" code }; }; var config = {}; config.meow = function() { // mock "meow" stuff }; var testcat = new cat(config); // 1 use mock "cat#meow" var realcat = new cat(); // 1 use prototype "cat#meow"
in above example, because of how javascript looks prototype chain, if sees implementation in class itself, it'll stop there , use method (thus, you've "overridden" prototype method). however, in example, if don't pass in config
, it'll way prototype cat#meow
method, , use one.
tl;dr: there's not 1 way implement javascript interfaces, ones double mocks (there's not best way implement dependency injection... that's foreign concept javascript itself, though many libraries implement cetain use-cases.)
Comments
Post a Comment