Friday, 31 January 2014

stubbing awkward jquery calls with sinon.js

We had an awkward bit of code at work the other day that called a third party control  like so:

function myObject(jsSelector) {
    return $(jsSelector).thirdpartycall({
            propertya: valuea,
            propertyb: valueb
    });
};



so if we want to test myObject, we are now stuck with the unfortunate jquery call inside.  not to worry, sinon.js to the rescue.  first i need to create a fake return object from that javascript call:

 var fakeResult = {
        propertya,
        propertyb,
        thirdpartycall: function (values) {
            this.propertya = values.propertya;
            this.propertyb = values.propertyb;
            return true;
        }
    };

what i do next is to stub jquery, and on using the selector it returns our fake object... yep how cool is that !
make sure when you write your test you wrap it like so (i had some fun with other tests failing after this as I had stubbed jquery permanently !!!)

it("should do something....", sinon.test(function () {

}));

then add the code:

it("should do something....", sinon.test(function () {
    $ = this.stub();
    $.withArgs('#myselector').returns(fakeResult);
}));
           
so now, if we call our object:

myObject('#myselector');

we then check fakeResult and the properties have been set.
Super awesome.



Wednesday, 13 November 2013

Form submissions in IE8 not working? check the buttons....

So for those of us who still have to put up with IE8 (Personally, i'd rather shoot myself in the face than have to deal with this nonsense) and your form submissions arn't working, check this little beauty:

<form>
      my form controls.....
      <button type="submit">mysubmitbutton and its icons</button>
</form>

click the submit button in IE 8 and no worky.... reason being is IE8 needs an input tag of type submit so if you find this, try changing your button to an input instead or at least putting a hidden input tag in there.

Joy !


Wednesday, 23 October 2013

Quick guide to debugging javascript with jasmine and Resharper 8

Hi everyone,

just to make our development lives a bit easier in javascript, i wanted to debug a jasmine test the other day and did a bit of stack overflowing and managed to get it working lovely, so here's the skinny :

Resharper 8 is really cool and comes with a whole host of functions, if you haven't already, check out the extension manager is so choc full of goodies e.g. angular plugins, nunit stuff, it made me cry.....

Anways, on with the show.  If you haven't already you will need to enable the jasmine support in the resharper menu :


Once done, we can get to writing our jasmine test, here's an example:

/// <reference path="../../BCAResearch/Scripts/jquery-1.7.1.js" />
/// <reference path="../../BCAResearch/Scripts/app/chart/ChartDataFunctions.js" />

describe("mytestsuite", function() {

    describe("When doingsomething", function() {

        it("It should do this", function() {

                jasmine.getEnv().currentRunner_.finishCallback = function () { };
            
            var dummySeriesCollection = new Array();
            var dummyseries = { series: 'theseries' };
            dummySeriesCollection.push(dummyseries);
            dummySeriesCollection.push(dummyseries);
            dummySeriesCollection.push(dummyseries);

            var panel1 = { SeriesCollection: dummySeriesCollection };
            chartData.Panels.push(panel1);

            var dummySeriesCollection2 = new Array();
            dummySeriesCollection2.push(dummyseries);
            dummySeriesCollection2.push(dummyseries);

            var panel2 = { SeriesCollection: dummySeriesCollection2 };
            chartData.Panels.push(panel2);

            expect(ChartDataFunctions.MaxNumberOfSeries(chartData)).toEqual(3);
        });
    });
});

notice the call to the jasmine.getEnv, this tells the call back never to happen leaving the connection open to resharper.

what we can do then is open up our favourite browser debugging tools, put a break point on our code (which is called tests.js) then hit F5 and presto ! debugging your test.

makes me smile....


Wednesday, 25 September 2013

Knockout keywords in IE8

So, we have a user base that is a majority share of IE8 users (i know, its depressing) and we are  suffering from a binding issue which turns out to be a knockout problem (well not a knockout problem, an IE8 being lame problem)

so if you are using knockout and IE8 and see a parsing issue with a knockout template e.g.

<tr data-bind="template: { name:'dataset-row-template', if: options.length > 0 }">

The offending bit is marked, change to 'if' and all should be happy.

Thursday, 4 July 2013

Beware the eyes of March (and missing event.PreventDefault)

Just a quick tip, I recently had a click event on an anchor tag and a get that loaded in some content when clicked like so:

$('#myid').click(function() {
     $.get('mvcurlhere', function (data) {
          //load my div here
      })
});

if you find yourself scratching your head when your MVC call using ajax and $.get seems not to be returning its because you didn't stop the original anchor from calling back, once more if your anchor tag has a # as the href which we all do from time to time, you will get the same page back with a # appended to the url and all sorts of great stuff starts happening my friends (especially with Chrome)

Solution ? remember the JQuery event.preventDefault call :

$('#myid').click(function(event) {

     event.preventDefault();    

     $.get('mvcurlhere', function (data) {
          //load my div here
      })
});

Happy days.....

Thursday, 16 May 2013

Example of mocking a job execution context in Quartz.net and Moq

I wanted to mock the IJobExecution context for my Quartz job today and wanted to use some of the job parameters, there is a little bit to setup, so here's an example of a starting point:

The Trigger

This is simple enough, create an object that implements ITrigger, I called mine "FakeTrigger", here i've only impelmented the StartTimeUTC



   public class FakeTrigger : ITrigger
    {
        public object Clone()
        {
            throw new NotImplementedException();
        }

        public int CompareTo(ITrigger other)
        {
            throw new NotImplementedException();
        }

        public IScheduleBuilder GetScheduleBuilder()
        {
            throw new NotImplementedException();
        }

        public bool GetMayFireAgain()
        {
            throw new NotImplementedException();
        }

        public DateTimeOffset? GetNextFireTimeUtc()
        {
            throw new NotImplementedException();
        }

        public DateTimeOffset? GetPreviousFireTimeUtc()
        {
            throw new NotImplementedException();
        }

        public DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTime)
        {
            throw new NotImplementedException();
        }

        public TriggerKey Key
        {
            get { throw new NotImplementedException(); }
        }

        public JobKey JobKey
        {
            get { throw new NotImplementedException(); }
        }

        public string Description
        {
            get { throw new NotImplementedException(); }
        }

        public string CalendarName
        {
            get { throw new NotImplementedException(); }
        }

        public JobDataMap JobDataMap
        {
            get { throw new NotImplementedException(); }
        }

        public DateTimeOffset? FinalFireTimeUtc
        {
            get { throw new NotImplementedException(); }
        }

        public int MisfireInstruction
        {
            get { throw new NotImplementedException(); }
        }

        public DateTimeOffset? EndTimeUtc
        {
            get { throw new NotImplementedException(); }
        }

        public DateTimeOffset StartTimeUtc
        {
            get { return new DateTimeOffset(DateTime.Now); }
        }

        public int Priority
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public bool HasMillisecondPrecision
        {
            get { throw new NotImplementedException(); }
        }
    }


Creating the context

This is simply a Moq IJobExecutioncontext

_mockJobExecutionContext = new Mock<IJobExecutionContext>();

Creating the Job Detail

A bit more unknown is the JobDetail object, but this is a new JobDetailImpl object :

_jobdetail = new JobDetailImpl("jobsettings", typeof (IJob));

We can then set up the get of this using Moq:


_mockJobExecutionContext = new Mock<IJobExecutionContext>();
_mockJobExecutionContext.SetupGet(p => p.JobDetail).Returns(_jobdetail);


We can also set up the job details such as description and key etc.


_mockJobExecutionContext.SetupGet(p => p.JobDetail.Description).Returns("jobdescription");
_mockJobExecutionContext.SetupGet(p => p.JobDetail.Key).Returns(new JobKey("jobkey",       
         "jobkeyvalue"));

The Job Data Map

The job data map is the settings that get passed to the job, this is a JobDataMap object but is instanciated with a list of key value pairs :


IDictionary<string, object> keyValuePairs = new Dictionary<string, object>();
keyValuePairs.Add("fromAddress", "fromaddress@email.org");
keyValuePairs.Add("toaddress", "toaddress@email.org");
JobDataMap jobDataMap = new JobDataMap(keyValuePairs);

We can then set the get up of that :

_mockJobExecutionContext.SetupGet(p => p.JobDetail.JobDataMap).Returns(jobDataMap );

Wrapping up 
Finally set up the remining bits such as the trigger

_mockJobExecutionContext.SetupGet(p => p.Trigger).Returns(_trigger);

Then we can test :

job.Execute(_mockJobExecutionContext.Object);

Hurah !