So, we now have an ASP.NET MVC web application which is hosting a simple Hello Angular World App. and in limiting the project size and complexity it should serve as a useful “starter template”. When looking at the project, you will notice two distinct naming conventions, initially I thought this was ugly, however it has proven a useful reminder of which environment or language we are dealing with e.g. TypeScript/JavaScript or C#.
Now we have an Angular 2 app running in our Local IIS (or IIS Express if you decided to skip that section), let’s build a very simple MVC app to host our Angular 2 app.
Add a Controller
Expand the Angular.World project
Right-click Controller…
Click Add > Controller
Select MVC 5 Controller – Empty
Click Add
Enter HomeController for the Controller name
Click Add
Add a Layout
Expand the Angular.World project
Right-click Views
Click Add > New Folder
Rename the folder Shared
Right-click Shared
Click Add > MVC 5 Layout Page (Razor)
Enter _Layout for the Item name
Click OK
Change the code to match:
Note: At this point you may notice that the @Styles is underlined in red, this is because the project is missing a reference, which we will address soon.
Save and close
Add the _ViewStart View
Expand the Angular.World project
Right-click Views
Click Add > MVC 5 View Page with Layout (Razor)
Enter _ViewStart for the Item name
Click OK
Note: The “\Views\_ViewStart.cshtml” file defines the common or default layout that all the application’s views will use. It is however possible to set a different layout by setting the Layout property, or setting it to null to not use a layout at all.
Add the Index View
Expand the Angular.World > Views project
Right-click Home
Click Add > MVC 5 View Page with Layout (Razor)
Enter Index for the Item name
Click OK
Double-click Index.cshtml
Copy and paste the following code:
Click Save and close
Install Microsoft.AspNet.Web.Optimization using NuGet
Tip: You can monitor the installation process using Visual Studio’s Output window
Update Web.config Files
Now that the project references System.Web.Optimization, we need to update the two Web.config file.
Root Web.config
Locate the config file located at the root of Hello.Angular.World project
Open the config file
Locate the configuration/runtime/assemblyBinding section
Add the following code
Note: …/runtime/assemblyBinding represents the path to a specific XML node…
Views Web.config
Locate the config file located within the Views folder
Open the config file
Locate the configuration/system.web.webPages.razor/pages/namespaces section
Add the following code
Note: …/pages/namespaces represents the path to a specific XML node…
_Layout.cshtml Review Code
Locate Views > Shared > _Layout.cshtml
Double-click cshtml to open
Locate the @Styles tag
The @Styles tag should no longer have a red underliner
Add the BundleConfig Class
Within the Angular.World project
Right-click App_Start
Click Add > Class…
Select Class
Enter cs
Click Add
Open cs
Replace the existing code with the following:
Save and close
Update the Global.asax
At this point we have written the code required to implement Bundling, however the web application doesn’t know about it, so let’s register it.
Within the Angular.World project
Double-click asax to open
Locate the Application_Start() method
Add the following code
One final thing: systemjs.config.js
Remember the “ASP.NET MVC: prefix / to specify the root” comment and that I said we would revisit systemjs.config.js file?
In the root of Angular.World project
Double-click config.js to open
Locate ‘npm:’: ‘node_modules/’ and change to: ‘npm:’: ‘/node_modules/’
Locate app: ‘app’, and change to: app: ‘/app’,
Save and close
TO-DO: I’m sure with a little effort we could write a Routing module to take care of this dynamically…
Test the Hello Angular World app
Select Angular.World and right-click
Click Properties or Alt+Enter
Click on Web
Set the Start Action to Current Page
Press Ctrl+S
Click Debug > Start Debugging or press F5 key
Visual Studio should build your project and open the default view in a Web Browser in debug mode. It is normal for IIS to take some time to load the web application, the first time it is run (i.e. either after an IIS reset, Web config change or an application build) …
We are sending a request to http://localhost:12345 which should load the default MVC View which in turn should load the Hello Angular World app:
Next try sending a request to http://localhost:12345/Home which should also load the default MVC View which in turn should load the Hello Angular World app:
And finally try sending a request to http://localhost:12345/Home/Index which should also load the default MVC View which in turn should load the Hello Angular World app:
My preference it to develop web applications using my Local IIS server opposed to the IIS Express server that ships with Visual Studio. I have several reasons for this, two of which are:
You have more control over how your application is served, for instance domain names and port numbers
You can test your web applications even if Visual Studio is not running
Now that the basic configuration is complete let’s create the Hello Angular World app. The table below lists the folders and files that we will add next.
Name
Type
Used
assets
Folder
Images etc. used by the Angular application
shared
Folder
Components shared across the Angular application
app.component.css
file
The main CSS file for the Angular application
app.component.ts
File
The main display template for the Angular application
app.module.ts
File
Imports the components and modules used by the Angular application
main.ts
File
The Angular application’s entry point
Add Folders & Files
Expand the Hello.Angular.World project and right-click on app
Click Add > New Folder for the following:
Assets
shared
Click Add > StyleSheet for the following:
app.component.css
Note: When a file name includes an extra full-stop, then you need to include the file extension as part of the name.
Click Add > TypeScript File for the following:
app.component.ts
app.module.ts
main.ts
Note: If you see the following alert, click No
Add Code to the App Files
Open app.component.css and add the following code:
Open app.component.ts and add the following code:
Open app.module.ts and add the following code:
Open main.ts and add the following code:
Update Test HTML File
Expand the Hello.Angular.World project
Double on the _index.html file to edit
Locate the following line of code: //System.import(‘app’).catch(function(err){ console.error(err); });
Uncomment the code by removing the prefixed //
Test the Hello Angular World app
Select Angular.World project and right-click
Click Set as Start Up Project
Select _index.html file and right-click
Click Set as Start Up Page
Click Debug > Start Debugging or press F5 key
Visual Studio should build your project and open the selected Web Browser. The _index.html may take time to load the first time and should look something like this:
Note: In my IIS Express example the URL is http://localhost:15426/_index.html, however your website maybe hosted on a different port number.
Now to add the basic folder and files structure required to build a simple Angular App. My intentions are to remain true to the conventions set out by Angular while remaining sympathetic to ASP.NET MVC. The items in grey were included automatically during the projects creation, the items in black we have already added and the items in red we are about to add.
Name
Type
Used
Origin
Added
app
Folder
Container for the Angular App files
Angular
Manually
App_Data
Folder
Included during the project creation
ASP.NET MVC
VS Template
App_Start
Folder
Included during the project creation
ASP.NET MVC
VS Template
Content
Folder
CSS files and related image files
ASP.NET MVC
Manually
=> site.css
File
Add to the Content folder
General
Manually
Controllers
Folder
Included during the project creation
ASP.NET MVC
VS Template
Images
Folder
Included during the project creation
ASP.NET MVC
VS Template
Models
Folder
Included during the project creation
ASP.NET MVC
VS Template
Scripts
Folder
JavaScript files
General
Manually
Views
Folder
Included during the project creation
ASP.NET MVC
VS Template
_index.html
File
HTML test page for Angular
General
Manually
Favicon.ico
File
Favourite or shortcut icon/images
General
VS Template
Global.asax
File
ASP.NET application file
ASP.NET MVC
VS Template
package.json
File
NPM package configuration
Quick Package Installer
NPM
Packages.config
File
NuGet package configuration file
ASP.NET MVC
VS Template
systemjs.config.js
File
Angular App configuration file
Angular
Manually
tsconfig.json
File
TypeScript configuration file
TypeScript
Manually
Web.config
File
Web application configuration file
ASP.NET MVC
VS Template
Added Default Folders
Select Hello.Angular.World and right-click
Click Add > New Folder
Give or rename the folder to match one of the following and repeat until the list is complete:
You may notice two comments containing “ASP.NET MVC: prefix / to specify the root”. This is to remind us to add the “/” prefix when we start working with MVC files.
Added Test HTML File
In readiness to test our Hello Angular World app, lets add an HTML file.
Select Hello.Angular.World and right-click
Click Add > HTML Page
Set the Item name: _index.html
Click OK
The default HTML code will look like this:
Update the code so that it looks like this:
Notice that the “System.import(‘app’).catch(function(err){ console.error(err); });” has been commented out, we will return to this section of code later.
Add Site.css file
Before I forget, let’s add a style sheet called Sites.css
Within the Hello.Angular.World project, right-click Content
Now that we have a basic ASP.NET MVC 5 project let’s install some NPM Packages. Once you have installed the first NPM Package you will see a new file, called package.json, added to your Project’s root. We will look at the package.json in more details later.
Install TypeScript 2 Package
To give you an idea of how to install NPM Package, let’s use the TypeScript 2 NPM Package as an example you can follow for all the other packages.
Select npm, enter typescript and select latest version (in this case 2.1.4)
Click Install
Tip: You can monitor the installation process using Visual Studio’s Output window
Note: TypeScript is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to clean, readable, standards-based JavaScript. Try it out at http://www.typescriptlang.org/playground.
Edit the ‘package.json’ File
Now that you have installed a NPM Package locate the package.json file at the root of the Hello.Angular.World project.
Open the package.json file in Visual Studio (text editor) and review the content
Change the value for “name“, from “myproject” to “hello-angular-world“
Add “description”: “Hello Angular World (from Visual Studio and Local IIS) is a start-up project in which two worlds collide… “
Add “license”: “MIT”
Add “repository”: {} or add your Git details…
Add “scripts”: {} and leave it empty for now
Add “dependencies”: {} and leave it empty for now
Move “devDependencies” : { “typescript”: “^2.1.4” } to the end (this is just a personal preference not requirement)
Before we continue with the process of adding PMN Packages I would like to point out that the Quick Install Package tool seems to always add the package reference to the devDependencies section. I am assuming this is in order to avoid adding unnecessary packages to test harnesses or transpilers the production app. You can read more here: https://docs.npmjs.com/files/package.json
Add “dependencies” Packages
The following packages should be added to the dependencies section, however as I mentioned earlier they are added to the devDependencies section and so we need to manually update the package.json file once we have finished importing the list.
Warning: The Quick Install Package’s Latest Version drop-down-list is not sorted numerically (the data is as string values and not number).
Tip: You can monitor the installation process using Visual Studio’s Output window
Open the package.json file in Visual Studio (text editor)
Review the contents, however there shouldn’t be any further actions to complete
Close the file
Restore NPM Packages
Just as we sometime need to restoring NuGet packages, we also need to restore NPM packages too.
Navigate to root of the Angular.World project
Right-click package.json
Click Restore Packages
Tip: You can monitor the installation process using Visual Studio’s Output window
Once the restoration process is complete, then the Hello.Angular.World project should contain a hidden folder called node_modules, see the image above for details.
Update the “scripts” Property (package.json)
This section can contain a list of script commands that automate life cycle processes for your package. For more information: https://docs.npmjs.com/misc/scripts
Navigate to the root of the Angular.World project
Open the package.json file in Visual Studio (text editor)
Add the following properties/commands:
Save and close the file
‘tsconfig.json’ file
Now that we have our NPM packaged loaded, lets configure the TypeScript configuration file. The tsconfig.json file instructs the compiler on how to generate JavaScript files.
Hello Angular World (from Visual Studio and Local IIS)
I have written this article and the accompanying Visual Studio 2015 project as an exploration of how Angular 2 and ASP.NET MVC 5 can coexist and I have tried to remain true to both frameworks, respecting naming conventions and file structure. While carrying out research for this article, I came across the Angular2Mvc5Application Project Template which did tick most of the boxes, however I wanted to know more about the inner workings, structure and naming conventions.
As you will see I have covered a lot of detail, so you may decide to download the source code to dip in and out as you need, or to read the article from end to end. Either way, the complete source code and project files can be found on GitHub: https://github.com/sionjlewis/Hello.Angular.World
Note: You may notice references to My.iTunes within the code, this is because I extracted this code from another solution with the sole purpose of keeping the example as simple as possible.
Turn on the Internet Information Services Windows Feature.
This action is only required if you plan to develop against your Local IIS server, opposed to IIS Express which ships with Visual Studio.
Configure Visual Studio to use the global external web tools, and not the tools that ship with Visual Studio:
Open Visual Studio 2015 and click: Tools > Options
Navigate to: select Projects and Solutions > External Web Tools
Add the nodejs Program Files directory at the top of the Locations of external tools list. In my case this path is C:\Program Files\nodejs Note: Visual Studio will now look first for external tools in the current workspace, if not found it will then look in the global path and if it is not found there, Visual Studio will use its own versions of the tools.
From: https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html#!#prereq1
Locate the short cut or favourite that you use to open Visual Studio
Right-click and click Properties
Click Shortcut > Advanced…
Tick the Run as administer checkbox
Click OK
Note: You may run into difficulties debugging without Run as administer, however depending on your UAC settings you are likely to see a User Access Control promote every time you open Visual Studio. Click Yes to continue to open Visual Studio.
Restart Visual Studio
Note: It is probably a good idea to restart your machine after the next section
NPM Task Runner & Package Installer
Install the following Visual Studio Extensions (if not already installed):
Note: I couldn’t find the Task Runner Explorer window at first, however after restarting my machine and some mucking around I found here: View > Other Windows > Task Runner Explorer (Ctrl+Alt+Bkspace)
Create a Visual Studio Project
At this point I am assuming you have completed the prerequisites and have Visual Studio 2015 open and ready to create a new project (and solution).
Select: File > Add > New Project…
Select: Visual C# > Web > ASP.NET Web Application (.NET Framework)
Note: At the time of writing this I had .NET Framework 4.6.1 installed
These are my notes, made while watching Deborah Kurta’s Angular2: Getting Started course, hosted by Pluralsight. Most, if not all, of this information can be found within Deborah’s course, however by stripping this information out I hope to jog memories…
Once complete, open the folder with Visual Studio Code.
Commit changes:
From Visual Studio Code select Push
If VS Code does not prompt for login and password, open the Terminal in the context of the code:
a. Select Explorer
b. Right click on a file in the root of the folder and click Open in Terminal
c. Enter the following command:
Mac:GitHub sion$ git push
d. Enter the Username and Password for your GitHub account
e. Wait for the command to complete before restarting VS Code
f. VS Code should now be able to Push without errors
g. Optional: install a credential helper https://help.github.com/articles/caching-your-github-password-in-git/
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
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”
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.
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..?
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: 1, 2, 3
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)
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
Right click on the ZIP file and “Extract All…“
Navigate to the “dist” directory and extract the latest ZIP file, in my case this is: jasmine-standalone-2.0.3.zip.
Open extracted folder and navigate to the “lib\ jasmine-2.0.3” directory.
From the root of the VS Project, navigate to the “Scripts” folder and add a sub-folder “jasmine“.
Copy the following files from “lib\ jasmine-2.0.3” to “Scripts\jasmine” folder:
boot.js
console.js
jasmine-html.js
jasmine.js
Back to the root of the VS Project, navigate to the “Content” folder and add a sub-folder called “jasmine“.
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
From the root of the VS project, navigate to “Scripts\jasmine” and add a sub-folder called “helpers“
Extract the jasmine-jquery-master.zip file
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.
Add a new “MVC5 Controller – Empty” file to your project called “JasmineContoller“
Within the “Views” folder add a new sub-folder called “Jasmine”
Add a “MVC 5 View Page (Razor)” called “SpecRunner”
Open JasmineContoller.cs and
Optionally add “using Microsoft.SharePoint.Client;” at top of the file.
Rename “public ActionResult Index()” to be “public ActionResult SpecRunner()“
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:
Fixtures to be added under Scripts/jasmine
this folder will contain any fixture file you have created for your specs.
Specs to be added under Scripts/jasmine
the folder will contain all your specs files.
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.
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: 1, 2, 3
You must be logged in to post a comment.