How to use dependency injection for testing?

I have piece of code in js like this:

var obj = (function(){ var stateObj = {key:"privateValue"}; return { getState: function() { return stateObj.key; }, publicFn : function(){ //do some operation with stateObj if(getState() == "test") { //. . . . } } } }());

and I tested the code like this:

//test case sandbox.stub(obj.getState,"test") assertItShouldGoInsideIfLoop(obj.publicFn())

However on the code review, my team lead said, this is wrong and he asked me to use Dependency injection for these cases.

I really don't know why the above approach is wrong or even why one should use DI.

-------------Problems Reply------------

If I'm interpreting this correctly, the issue here is that your test for the value of calling publicFn depends on the value of stateObj. The entire idea behind dependency injection is that you provide some means to supply these values in your tests in order to decouple the data from the behavior of the function under test.

var obj = (function(){
return {
setStateObj: function(stateObj) {
this.stateObj = stateObj;
},
getState: function() {
return this.stateObj.key;
},
publicFn : function(){
//do some operation with stateObj
if(getState() == "test") {
//. . . .
}
}
}
}());

Now we can use setStateObj to set the state as needed in our tests instead of stubbing the value, which can be dangerous:

obj.setStateObj({ key: 'test' })
assertItExecutesIfStatement(obj.publicFn())

obj.setStateObj({ key: 'blah' })
assertItDoesntExecuteIfStatement(obj.publicFn())

So why is this preferred to stubbing getState? Say we comment the contents of getState:

getState: function() {
// return this.stateObj.key;
}, // returns nothing, but you're stubbing it to return "test" anyway!

Clearly, this function will not work, but with your stub, it will! So you'll have passing tests despite the non-working code!

Here's another example that makes another case for dependency injection. Say I have the following function:

function getDayOfWeek() {
var date = new Date();
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
return dayNames[date.getDay()];
}

This getDayOfWeek function is dependent on date. This would be a nightmare to test since we have no control over date's value. If we rewrite this function with a way to supply a date value (i.e. inject the dependency), we can check test the function for any fixed date easily:

function getDayOfWeek(date) {
date = date || new Date();
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
return dayNames[date.getDay()];
}

assertEqual('Wednesday', getDayOfWeek(new Date(2015, 0, 1)));
assertEqual('Thursday', getDayOfWeek(new Date(2015, 0, 2)));
// and so on...

Category:javascript Views:0 Time:2018-07-10

Related post

  • How to use Dependency Injection for creating ViewModels in a Master-Detail view 2011-08-25

    I'm building a Silverlight app using Jounce for my MVVM. I have a CustomerListViewModel (plural) which has a collection of CustomerViewModel objects (single). I'm using Ninject for dependency injection, because my ViewModels will be depending on othe

  • GWT MVP when & how to use Dependency Injection 2010-11-12

    We're using the MVP pattern and GWT and I'm wondering how and when dependency injection should be used. We have an App Controller, Presenters, Views and Model code. From reading the GIN tutorial at http://code.google.com/p/google-gin/wiki/GinTutorial

  • How to solve base Controller dependency injection for testing purposes? 2009-09-17

    I have implemented my mvc base controller called DefaultController using dependency injection pattern in order to be able to construct test cases. Example below: public class DefaultController : Controller { protected readonly ISessionHelper _session

  • How to use Dependency Injection without breaking encapsulation? 2010-09-29

    How can i perform dependency injection without breaking encapsulation? Using a Dependency Injection example from Wikipedia: public Car { public float getSpeed(); } Note: Other methods and properties (e.g. PushBrake(), PushGas(), SetWheelPosition() )

  • How to use Dependency Injection with ASP.NET Web Forms 2009-02-26

    I am trying to work out a way to use dependency injection with ASP.NET Web Forms controls. I have got lots of controls that create repositories directly, and use those to access and bind to data etc. I am looking for a pattern where I can pass reposi

  • Not sure how to use Dependency Injection + Repository Pattern + Unit Of Work Pattern with a WinForm application 2010-02-21

    (apologies for the Wall Of Text... :) ) Summary Using Dependency Injection with my Winfor application is creating a large number of Repository Context's. I'm not sure if the way i'm using this is right or wrong, or what the common practice is. Detail

  • How to use Dependancy Injection when dependant class is not known at Registration? 2011-10-19

    I have few questions about Dependency Injection using Unity Framework 1>Does each class always need default constructor? 2>How do we register a class whose dependent class is not known at the time of registration but it will become avialble at

  • I know how to use dependency injection but I recognize no practical advantage for it 2011-09-08

    It is about this (Inject the dependency) private readonly ICustomerService _customerService; public Billing(ICustomerService customerService) { _customerService = customerService; } versus this (Create the dependency) private readonly ICustomerServic

  • How do I use dependency injection for external dependencies? 2011-09-22

    I think I almost got this. Say I want my app to send SMSs. But Im not sure yet if I should go with Twilio or SomeOtherSMSService. In fact, I dont really care yet. So I have something as simple as this so I could keep developing my app. public interfa

  • How to use dependency injection in Zend Framework? 2010-09-05

    Currently I am trying to learn the Zend Framework and therefore I bought the book "Zend Framework in Action". In chapter 3, a basic model and controller is introduced along with unit tests for both of them. The basic controller looks like this: class

  • How to use Dependency Injection with Static Methods? 2011-06-29

    Imagine there is a Customer class with an instance Load() method. When the Load() method is called, it retrieves order details by e.g. var orders = Order.GetAll(customerId, ...); GetAll() is a static method of the Order class and the input parameters

  • How to use dependency injection with an attribute? 2010-11-04

    In an MVC project I'm creating I have the following RequirePermissionAttribute that gets put on any action that needs specific permissions (it's been simplified for this example): public class RequirePermissionAttribute : ActionFilterAttribute, IAuth

  • How to use Dependency Injection and not Service Locator 2011-03-28

    I am hearing people say you should not use Service Locator for your Dependency Injection. So how exactly do you inject the dependencies without relying on a service locator? I want to try out IoC containers, but don't want to land into an anti-patter

  • Use dependency injection for Properties.Settings.Default? 2011-08-19

    Should you consider the use of Properties.Settings.Default within a class as a dependency, and therefore inject it? e.g.: public class Foo { private _settings; private bool _myBool; public Foo(Settings settings) { this._settings = settings; this._myB

  • How to use dependency injection with Zend_Soap_AutoDiscover 2011-11-18

    I'm trying to use a dependency injection container for the first time in a project, but I just discovered a problem that I'm not sure how to address. The project provides a SOAP web service, which is implemented atop the SOAP component of Zend Framew

  • What are the best practices for class libraries using dependency injection for internal operations? 2009-12-02

    What should I be careful about when building a class library complex enough to use internal dependency injection? Assuming that it will use Castle Windsor (as an example), what would be the best place/method to configure the container, given that the

  • using dependency injection for Entity Framework 4.1 along with "Unit of Work" and "Repository" patterns 2011-12-28

    I have seen various implementations for Entity Framework using unit of work and repository patterns. ideally I want to use interfaces for unit of work, database context, repository (for both generic and specific repositories) and instantiate them in

  • How to enable Dependency Injection for ServiceRoute in MVC3 and WCF Web API 2011-07-19

    I am creating a MVC3 website that will expose a REST API using WCF Web API. To register routes to the REST API I add code to the Global.asax similar to the code below. routes.MapServiceRoute<RelationsService>("relations"); This works well enoug

  • Perl - Test::Unit::Lite, how to use multiple folders for test files 2010-08-24

    I use Test::Unit::Lite for unit testing in Perl. Now, this module looks for .pm files in t/tlib. However, I have several tests for the project and I would like to separate them in folders like: t/tlib/Unit_Tests/...pm, t/tlib/Functional_Tests/...pm a

  • How to use Omniauth + capybara for testing FB Connect? 2011-08-30

    I have a rails 3 app + devise using capybara for integration tests. Right now I have sign and sign up tests working but don't have tests for FB Connect. How can I add Omniauth tests to ensure sign up and sign in work? Any one have an example or a up

  • How to do dependency injection python-way? 2010-04-27

    I've been reading a lot about python-way lately so my question is How to do dependency injection python-way? I am talking about usual scenarios when, for example, service A needs access to UserService for authorization checks. --------------Solutions

  • Using dependency injection in a library 2009-04-03

    I'm writing a java library that will be used by an existing application. I'm using dependency injection so testing is easier, and I'm familiar with Spring so I was planning to use it to manage the dependency injection while testing. The applications

  • Dependency Injection for objects that require parameters 2010-04-03

    All of our reports are created from object graphs that are translated from our domain objects. To enable this, we have a Translator class for each report, and have been using Dependency Injection for passing in dependencies. This worked great, and wo

  • Where to keep dictionaries in app using Dependency Injection 2012-02-02

    I have a legacy code, and I have a problem with reconstructor it. At start of my application I load from WCF to property on App (this is SL application) list of users. Then every control (for sending emails, view calendar and assigning tasks) use thi

  • Can you use dependency injection everywhere a singleton is needed? 2010-07-04

    This may sound like a stupid question, but can DI be used everywhere where a Singleton is needed? Or are there use cases where a Singleton makes more sense? A professor of mine said that there a few but valid cases where a Singleton is "good enough"

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.164 (s). 11 q(s)