1

Given the following Javascript, would it be better/more idiomatic to inject the MyService object into myMethod so that a fake version of MyService could be injected for testing? Or am I missing something?

var myObject = {
  myMethod: function() {
    var myService = new MyService();
    return myService.doSomething();
  }
}

1 Answer 1

1

Dependency injection always takes precedence over hard-coding the dependencies. Also, by coding to interfaces (assuming the myObject instance has been given a copy of a Service object that has a doSomething() method) could come handy here.

Sign up to request clarification or add additional context in comments.

3 Comments

By "interface" I presume you mean that the prototype of MyService is set to Service? Given that methods can be changed dynamically in JS, what are the benefits of this approach over and above simply re-defining (say) doSomething in my test?
Exactly. It has no performance gains. It only makes your program more readable by allowing the reader to understand the contract (interface) and then follow the logic inside the implementation.
No problem. I hope I've been able to help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.