Monthly Archives: September 2014

Jasmine with Visual Studio and SharePoint Apps – Part 3

Jasmine Fixtures and Chutzpah Test Adaptors

In my last post I described how to configuring an “App for SharePoint” VMC project to use Jasmine and Jasmine-Jquery for BDD with Visual Studio using Chutzpah Test Adaptor or a Web Browser. In this post I want to talk about Fixtures and a major pitfall I’ve found when working with Chutzpah Test Adaptor for the Test Explorer.

How to Install Chutzpah Test Adaptor

1. Install VS Extensions
Open Visual Studio 2013 > TOOLS > Extensions and Updates…

Within the Left panel, click on Online and search for Chutzpah Test

Download:

And then restart Visual Studio

2. Configure Test Explorer

Open Visual Studio 2013 > TEST > Windows > Test Explorer and pin the window to suite your preference…

Top left of the Test Explorer window, click on the button “Run Test After BuildRun Test After Build

Why Chutzpah Test Adaptor?

Chutzpah Test Adaptor for the Test Explorer is an extremely popular open source extension for Visual Studio that enable developers to run Jasmine and other test frameworks directly within Visual Studio Test Explorer.

Side note: Chutzpah Test Adaptor uses the PhantomJS headless browser to run your tests.

This is incredibly useful for developer as we can quickly configure VS Test Explorer to display the results of changes made to either Spec or Source upon saving. And the process up to the point we want to introduce Fixtures to our Specs is greater, however that is where the problems start…

What are Fixtures?

A set of functions included with Jasmine-JQuery that enables developers to injecting “fixtures” into the DOM to be cleaned up after each spec. Fixtures can be HTML, CSS or JSON and either written inline or loaded up from an external file.

When Would Load a File as a Fixture?

If for example you need to write a Spec that described a User accessing his/her colleague’s User Profile Page, it may not be possible to guaranty available or stable of the test data in a development environment. In which case we would generate a JSON file and save it to the Fixtures folder (see Part 2) and load the data up before each “IT” case was run.

What’s The Problem?

When you test you Spec using the SpecRunner View/Page within a Web Browser Fixtures work fine and all the test pass or fail as expected. However when you attempt to run the same spec within Visual Studio using Chutzpah Test Adaptor the same test that passed now fail.

The reason for this because Chutzpah generates a HTML file on the fly and temporally saves it to the file system and therefore does not have HTTP or HTTPS address and as a consequence Jasmine-JQuery is unable to resolve a URL throwing an error.

Log Message: Error: Fixture could not be loaded: ../Scripts/jasmine/fixtures/filename.html (status: error, message: undefined) from c:\…\sjlewis.sharepoint.jasmine2web\scripts\jasmine\specs\fixtures_spec.js

Having done a little more digging it would appear the jasmine.Fixtures.prototype. getFixtureHtml_() function requires a URL which is either resolved as NULL or not being passed.

Side note: The "spcontext.js" script throws an error because window.location.href is null

The Workarounds

As there two possible three options that we may use to get around this limitation, however with option you choose will depending on the size of the data or DOM structure that you are wanting to testing your Specs against.

1.       Load data into the DOM using for example the setFixtures() function.

setFixtures('<div class="sandbox">hello there</div>');

This work fine in both in Visual Studio and a Web Browser. However writing large amounts of HTML structure in JavaScript is not ideal as it is time consuming and error prone.

2.       Attempt to load the file into the DOM using the loadFixtures() function but wrap the code in a try-catch block. I’ve highlighted the code of interest in red:

describe("Fixtures: Learning about", function () {
    beforeEach(function () {
        // You can configure this path to fixtures...
        jasmine.getFixtures().fixturesPath = '../Scripts/jasmine/fixtures';
    });

    it("offers three crucial functions", function () {
        expect(readFixtures).toBeDefined();
        expect(setFixtures).toBeDefined();
        expect(loadFixtures).toBeDefined();
    });

    // Fails to run within "Chutzpah Test Adaptor for the Test Explorer".
    it("can load fixtures from a file", function () {
        try {
            loadFixtures('filename.html');
            expect($('#jasmine-fixtures')).toExist();
        } catch (ex) {
            console.log("#### ERROR: [" + ex + "]");
        }
    });

    // Fails to run within "Chutzpah Test Adaptor for the Test Explorer".
    it("can read fixtures without appending to DOM", function () {
        try {
            var fixture = readFixtures('filename.html');
            expect(fixture).toContain('p');
            expect($(fixture).find('p')).toHaveText('Hello World');
        } catch (ex) {
            console.log("#### ERROR: [" + ex + "]");
        }
    });​

    it("can also receive the fixture as a parameter", function () {
        setFixtures('<div class="sandbox">hello there</div>');
        expect($('.sandbox')).toExist();
    });

    it("offers a sandbox function for convenience", function () {
        expect(sandbox).toBeDefined();
        setFixtures(sandbox({ 'class': 'some-class' }));
        expect($('.some-class')).toExist();
        expect($('#sandbox')).toHaveClass('some-class');
    });
});​

So none of the Specs calling the loadFixtures() function will fail anymore when tested within Visual Studio, however  just like a false negative the false positive would not be tested for within the a Web Browser.

3.       Look at using jasmine-fixture, apparently this helper library may reduce the about of HTML required to write when creating a DOM structure inline, however it may not be of any use for writing JSON..?

jasmine-fixture

https://github.com/searls/jasmine-fixture

Conclusion

So when dealing with large amounts of data or complicated DOM structure option2 may be the best bet however we will need to decide on how to deal with false positive or negatives… As for small amount of data then option3 may prove to be better than option1 however further investigation is required.

Looking longer term, this area of development is becoming more and more popular as development teams continue on their quest to reduce bugs I’m sure solutions will be found.

Jasmine with Visual Studio and  SharePoint Apps​ – Part: 123

Useful Links​

Jasmine 2.0 Documentations
http://jasmine.github.io/2.0/introduction.html

Jasmine.JS Download
https://github.com/pivotal/jasmine

Jasmine-JQuery.JS Download
https://github.com/velesin/jasmine-jquery

Chutzpah JavaScript Test Runner
https://chutzpah.codeplex.com

Chutzpah Test Adapter for the Test Explorer
http://visualstudiogallery.msdn.microsoft.com/f8741f04-bae4-4900-81c7-7c9bfb9ed1fe

Chutzpah Test Runner Context Menu Extension
http://visualstudiogallery.msdn.microsoft.com/71a4e9bd-f660-448f-bd92-f5a65d39b7f0

jasmine-fixture
https://github.com/searls/jasmine-fixture

Uninstall Jasmine (NuGet Package)

Jasmine with Visual Studio and SharePoint Apps – Part 2

How to Structure a MVC Project (without NuGet)

Last week I wrote about how to configure Jasmine to run within Visual Studio using Chutzpah Test Adaptors. However since then I’ve run into a number of issues for which I will share my thoughts in this post.

The first of these is in regards to implementing Jasmine using NuGet. In the main I’m a big fan of NuGet, however when it comes lesser known frameworks such as Jasmine and Jasmin-JQuery the packages are either not available or most up to date. With that in mind I’ve decided to manage the Jasmin and Jasmin-Jquery manually using the steps described below.

Configuring an App for SharePoint Project

Step 1: Install Chutzpah

Skip this section if you have previously installed the Chutzpah Test Adaptor for the Test Explorer extension, as this action only needs to be carried out once per development environment.

As described in my previous post; install the Chutzpah Test Adaptors by opening Visual Studio 2013 > TOOLS > Extensions and Updates… Within the left panel, click on Online and search for Chutzpah Test and click “Download” for the following extension:

  • Chutzpah Test Adaptor for the Test Explorer
  • Chutzpah Test Runner Context Menu Extension

Once installed restart Visual Studio.

Step 2: Uninstall Jasmine (NuGet Package)

Uninstall Jasmine (NuGet Package)For existing projects only; removal of either the SharePoint Jasmine Test Runner or Jasmine Test Framework NuGet packages.

Open Visual Studio 2013 > TOOLS > NuGet Package Manager > Manage NuGet Packages for Solution… Within the left panel, click on installed packages and navigate to the package to remove (e.g. SharePoint Jasmine Test Runner) and click Manage.

A modal window will open; deselect the project(s) you would like to remove the package from and click OK.

Note: the NuGet Package may leave files and folders behind, which you will need to clean up manually.

Step 3: Add Jasmine & Jasmine-JQuery

To add Jasmine to a new or existing Visual Studio project, start by downloading the following libraries:

Note: in both cases I chose to download the “master” branch.

Jasmine

Solution Explorer

  1. Right click on the ZIP file and “Extract All…
  2. Navigate to the “dist” directory and extract the latest ZIP file, in my case this is: jasmine-standalone-2.0.3.zip.
  3. Open extracted folder and navigate to the “lib\ jasmine-2.0.3” directory.
  4. From the root of the VS Project, navigate to the “Scripts” folder and add a sub-folder “jasmine“.
  5. Copy the following files from “lib\ jasmine-2.0.3” to “Scripts\jasmine” folder:
    • boot.js
    • console.js
    • jasmine-html.js
    • jasmine.js
  6. Back to the root of the VS Project, navigate to the “Content” folder and add a sub-folder called “jasmine“.
  7. Copy the following files from “lib\ jasmine-2.0.3” to “Content\jasmine“:
    • ​​Jasmine.css
    • Jasmine_favicon.png

The structure of your VS project should now look similar the image on the right.

Jasmine-Jquery

  1. From the root of the VS project, navigate to “Scripts\jasmine” and add a sub-folder called “helpers
  2. Extract the jasmine-jquery-master.zip file
  3. Copy the jasmine-jquery.js file from the “lib” folder to the “Scripts\jasmine\helpers” folder.

At this point you have the relevant tools write and test Jasmine Specs from within Visual Studio and running the test(s) using the Chutzpah Test Adaptor for the Test Explorer extension. However due to some limitations which I will go into detail later, I would recommend adding Spec Runner page.

Step 4: Added a SpecRunner View

Navigate back the jasmine-standalone-X.X.X folder you will see a file called SpecRunner.html. In this section I will describe how to recreate this file within your MVC project.

  1. Add a new “MVC5 Controller – Empty” file to your project called “JasmineContoller
  2. Within the “Views” folder add a new sub-folder called “Jasmine”
  3. Add a “MVC 5 View Page (Razor)” called “SpecRunner”
  4. Open JasmineContoller.cs and
    • Optionally add “using Microsoft.SharePoint.Client;” at top of the file.
    • Rename “public ActionResult Index()” to be “public ActionResult SpecRunner()
  5. Open the SpecRunner.cshtml file and add the following reference in between HEAD tag:

Note: we will add our references to our Specs and Source files below the comments later on.

Step 4 Folder Structure

I’m sure you would agree when it comes to managing files a consistent structure is key. So we are going to add another 3 more folders to our project:

  1. Fixtures               to be added under Scripts/jasmine
    this folder will contain any fixture file you have created for your specs.
  2. Specs                 to be added under Scripts/jasmine
    the folder will contain all your specs files.
  3. Src                      ​to be added directly under Scripts
    this folder will contain all your custom JavaScript file for project.

So now the MVC (App for SharePoint) project should have a structure something like this:

MVC App for SharePoint Project​
        • Controllers​​
              • ​​JasmineController.cs
        • Scripts
              • Jasmine
                    • fixtures ​​
                          • helloWorld_fxtr.js
                    • helpers
                          • jasmine-jquery.js
                    • specs
                          • helloWorld_spec.js
                          • boot.js console.js
                          • jasmine-html.js
                          • jasmine.js
                    • Src
                          • helloWorld.js
                          • _jasmine_ref.js_references.js
                          • Jquery-X.XX.X.js
    • Views
            • Jasmine
                  • ​​​​​SpecRunner.cshtml

Getting Ready To Run Tests from Visual Studio

Before we attempt to run any tests you may remember from my previous post that we need to manage the references stored within the _reference.js file.

REMEMBER: to avoid Chutzpah running your tests more than once, you need to remove references to your Spec files from the _reference.js file (every time you add a new JS file).

We also need to add one or more references to the top of each Spec files to tell Visual Studio & Chutzpah which Source Scripts are to be referenced by a spec. For example the helloWorld_spec.js file need the following to reference to be able to run:

/// <reference path="src/helloWorld.js" />

As your Specs reference more and more source scripts and libraries, the spec files run the risk of become chocked up with references. To avoid that adding a reference to a file such as _reference.js file would work except it has one undesirable side effect. When referencing the _reference.js file directly from a Spec files I noticed the following error displayed at least twice:

Error: TypeError: ‘null’ is not an object (evaluating ‘getAuthorityFromUrl(window.location.href).toUpperCase’)

Which in turn cause a number of other false errors…

With that in mind taking a copy of the _reference.js file and renaming it to _jasmine-ref.js file and removing the following:

  • /// <autosync enabled=”true” />
    this is irrelevant within out custom file.
  • /// <reference path=”spcontext.js” />
    this is causing the multiple errors.

This is what my _jasmine-ref.js file looks like:

/// <reference path="modernizr-2.6.2.js" />
/// <reference path="jquery-1.10.2.js" />
/// <reference path="bootstrap.js" />​​

/// <reference path="respond.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

/// <reference path="knockout-3.2.0.js" />
/// <reference path="jasmine/boot.js" />
/// <reference path="jasmine/console.js" />
/// <reference path="jasmine/jasmine-html.js" />
/// <reference path="jasmine/jasmine.js" />
/// <reference path="jasmine/helpers/jasmine-jquery.js" />

/// <reference path="src/helloworld.js" />

Next then add the following reference at the top of each of your Spec files:

/// <reference path="../../_jasmine_ref.js" />​

Note: This workaround will not remove the error completely, but will reduce it to a single output.

Testing a Hello World Spec

When writing new code you need to get into the habit of writing a Spec first and then Source code to pass the test. So in this sections let write a simple Hello World Spec and Code:

  • Add a new JS file to the specs folder called helloWorld_spec.js
    (see folder structure above for details)
  • Open the helloWorld_spec.js and add the following code:
1.  /// <reference path="../../_jasmine_ref.js" />
2.
3.  describe("HelloWorld", function () {
4.    it("will return true", function () {​
5.             var result = firstTest();
6.             expect(result).toBe(true);
7.    });
8.  });
  • Open Test Explorer (TEST > WINDOWS > Test Explorer) and click on Run All and your test should fail. This is because you we have not written any code yet…
  • Add a new JS file to the src folder called helloWorld.js
  • Open the helloWorld.js and add the following code:
1.  "use strict";
2.
3.  var firstTest = function () {
4.    return true;
5.  }
  • Open Test Explorer and click on Run All and your test should now pass.

Congratulations you have just written a Spec and tested it within Visual Studio.

Getting Ready To Run Tests from a Web Browser

Fortunately the workarounds mentioned above are not required when running Jasmine Specs in a Web Browser. So remember back to the step “Added a SpecRunner View”, well we need to first add a reference each to your Spec and Source files, see my HelloWorld example code below:

​@{
Layout = null;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Spec Runner</title>

<meta name="description" content="Dispalays test results based upon from Jasmin specifciations" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<link rel="shortcut icon" type="image/png" href="/Content/jasmine/jasmine_favicon.png">

@Styles.Render("~/Content/jasmine/jasmine.css")
@Scripts.Render("~/Scripts/jasmine/jasmine.js")
@Scripts.Render("~/Scripts/jasmine/jasmine-html.js")
@Scripts.Render("~/Scripts/jasmine/boot.js")
@Scripts.Render("~/Scripts/jquery-1.10.2.js")
@Scripts.Render("~/Scripts/knockout-3.2.0.debug.js")
@Scripts.Render("~/Scripts/jasmine/jasmine.js")
@Scripts.Render("~/Scripts/jasmine/helpers/jasmine-jquery.js")
@Scripts.Render("~/Scripts/jasmine/helpers/jasmine-jquery.js")

<!-- include spec files here... -->

@Scripts.Render("~/Scripts/jasmine/specs/helloWorld_spec.js")

<!-- include source files here... -->

@Scripts.Render("~/Scripts/src/helloWorld.js")

</head>
<body>
</body>
</html>​

Once you have done that you are ready to hit [F5] and deploy your SharePoint App and run the MVC Project from IIS Express.

TIP: If like me you get fed up having to hit [F5] every time you want to test a Specs then update your MVC project to use the Local IIS. Just make sure that you specified https and not http for the Project URL.

Conclusion

So we have covered a lot of ground in this post, from downloading the latest Jasmine library and Jasmine-JQuery helper, to structuring the library files, specs, fixtures, helpers and source files, we also covered Visual Studio references and adding a SpecRunner View for in Browser Testing and finally we wrote a hello world test.

In “Part 3” I plan to cover Fixtures and a major pitfalls when testing Chutzpah in Visual Studio.​

Jasmine with Visual Studio and  SharePoint Apps​ – Part: 123

App for SharePoint project​

Jasmine with Visual Studio and SharePoint Apps – Part 1

This blog does no​t describe how to perform JavaScript ​TDD (test-driven development) or BDD (behaviour-driven development). It does however describe how to set-​​up Visual Studio and configure an App for SharePoint project to get you started.

1. Install VS Extensions

Open Visual Studio 2013 > TOOLS > Extensions and Updates…

Within the Left panel, click on Online and search for Chutzpah Test

Download:

  • Chutzpah Test Adaptor for the Test Explorer
  • Chutzpah Test Runner Context Menu Extension

And then restart Visual Studio

2. Configure Test Explorer

Open Visual Studio 2013 > TEST > Windows > Test Explorer and pin the window to suite your preference…

Top left of the Test Explorer window, click on the button  “Run Test After Build” Run Test After Build

Create a new App for SharePoint Project​

Now that we have Visual Studio configured and ready to go, we need an App for SharePoint project to work with.

Create a new App for SharePoint project​

App for SharePoint project​

Choose where to debug the App and the type: Provider-hosted

Choose where to debug the App and the type

The type for project to create: ASP.NET MVC Web Application

ASP.NET MVC Web Application

And finally the authentication model: Windows Azure Access Services

Windows Azure Access Services

And finally You will then be prompted to sign into the portal your specified earlier.​

Adding Jasmine JS to a Project​

Now that we have an App for SharePoint project lets add Jasmine.

1. Install NuGet Package

Open Visual Studio 2013 > TOOLS > NuGet Package Manager > Manage NuGet Packages for Solution…

Within the Left panel, click on Online and search for SharePoint Jasmine Test Runner and click download.​

Search for SharePoint Jasmine Test Runner and click download

Note: the SharePoint Jasmine Test Runner package was created by Thorston Hans and at the time of writing this blog it was at version 0.0.1 and contained Jasmine 2.0. My reason for choosing SharePoint Jasmine Test Runner over Jasmine Test Adapter was because it did not include the VMC files which are not required if you plan to testing your code directly in Visual Studio.​

2. Configure Files/Package

Navigate to the Scripts folder for each of projects you added the package too and you will notice a folder containing JS files called  jasmine-samples. You do not need this scripts or this folder, so select the it and right click to see the context menu and then click either Delete or “Exclude from Project“.

3. Other Files

The Content folder contains a new folder called jasmine containing a single CSS file, don’t need to do anything with this.​

4. How to use Jasmine

After adding the SharePoint Jasmine Test Runner package, start by adding a “spec” file to your scripts folder. Spec files are where you will  describe your application and are the basis of your tests. After writing each test, you will immediately write the code (e.g. a function) within your “source” file fore fill the spec and therefore cause the test to pass. You repeat this process over and over again until you have written one or possible more spec that describes your JavaScript Application. Once all the tests pass have successfully passed then your development is finished (in theory).

5. Naming Convention

Depending on the size and complexity of your project, you many have one or more spec and source files. I would recommend pairing up the files so that a spec file always as a source file and vice versa.

For example:

  • filename_spec.js              contains the specs used to test the code.
  • filename.js                         contains the source code used by the application

4. What to look out for

  • Keep your spec and source files paired up and within the same folder.
  • If you are seeing duplicated tests then make sure that spec files are not being referenced. For example check the _references.js file and remove any reference:
    /// <reference path="_tests/filename_spec.js" />
  • Visual Studio add automatically adds references to the _references.js file every time a new JS file is added to the Scripts folder. You will need to open the _references.js file​ and remove spec file​ references each time a new JS file is added.
  • If your test continue to fail even when they look correct, make sure that your spec file has a reference to its related source file:​
    /// <reference path="filename.js" />
  • To enable your test to run every time you save a file, click on the button “Run Test After Build” located at the top left of the Test Explorer window.

Jasmine with Visual Studio and  SharePoint Apps​ – Part: 123

Useful links
Video Tutorials