Category Archives: SharePoint 2013

Connect-PnPOnline: unwanted credential caching

UPDATE: May 2021

This problem, as described in my original post below, has been fixed for the Connnect-PnPOnline, when using the UseWebLogin param. Plus, the ClearTokenCache parameter is no longer available…

Connect-PnPOnline -Url "https://[tenant].sharepoint.com" -UseWebLogin; 

The “new” (or orignal) experience when calling the above Cmdlet will look like the following screen shot:

Login screen: That didn’t work … Here are a few ideas…

For more options, see https://pnp.github.io/powershell/cmdlets/Connect-PnPOnline.html#example-9

An alternative is to use the Interactive prameter:

Connect-PnPOnline -Url "https://[tenant].sharepoint.com" -Interactive; 

For more information, see https://pnp.github.io/powershell/cmdlets/Connect-PnPOnline.html#example-10

Original Post

Since creating a new Windows 10 profile (new PC) the Connect-PnPOnline PowerShell CmdLet has been caching my primary credentials while using the UseWebLogin parameter.

Connect-PnPOnline -Url "https://[tenant].sharepoint.com" -UseWebLogin; 

This wouldn’t be a problem if I only worked with on tenant…

After a fair amount of Google searching, mucking around with Internet Explorer and Microsoft Edge settings I found that running the Connect-PnPOnline CmdLet with the following parameters worked:

Connect-PnPOnline -Url "https://[tenant].sharepoint.com" -SPOManagementShell -ClearTokenCache;

Once signed you can revert back to using the UseWebLogin parameter, well until the next time the PowerShell console caches the wrong details… 😉

For more information see: https://docs.microsoft.com/en-us/powershell/module/sharepoint-pnp/connect-pnponline?view=sharepoint-ps

SharePoint Online Permissions

Overview of SharePoint Online’s “out-of-the-box” permissions:

Permission Restricted View Read Contribute Edit Design Full Control
Can view pagesYesYesYesYesYes Yes
Can view list items
and documents
YesYesYesYes Yes Yes
Download documentsNoYesYesYes Yes Yes
Can add, update
and delete list items
and documents
NoNoYesYes Yes Yes
Can add, edit and
delete lists
NoNoNoYes Yes Yes
Can approve
and customize
NoNoNoNoYes Yes
Has full controlNoNoNoNoNoYes

SharePoint Online permissions, listed in reverse order:

  • Restricted View
    View pages and documents, but not historical versions or user permissions
  • Read
    View pages and items in existing lists and document libraries and download documents
  • Contribute
    View, add, update, and delete list items and documents
  • Edit
    Add, edit, and delete lists; view, add, update, and delete list items and documents. By default, this permission level is assigned to the Members group
  • Design
    Create lists and document libraries, edit pages and apply themes, borders, and style sheets on the site. There is no SharePoint group that is assigned this permission level automatically
  • Full Control
    Contains all available SharePoint permissions. By default, this permission level is assigned to the Owners group. It can’t be customized or deleted.

For more information, see Microsoft pages:

SharePoint ‘Site Content and Structure’ Admin Page

There have been numerous time I’ve need to publish multiple documents in one go. You could use PowerShell or better still the UI…

Welcome to the Site Content and Structure administration page:
https://[TENANT].sharepoint.com/<SITE-PATH>/_layouts/15/sitemanager.aspx

The Site Content and Structure has been around since SharePoint 2007 and it really shows. But don’t let that get in the way of useful functionality. It is still available in SharePoint Online, even though the link has been removed from the Site Settings page.

Imagine you need to publish 50 site pages in one go:

  1. Navigate to the Site Content and Structure using the URL above
  2. Click on Site Pages, within the left navigation
  3. Select the pages to publish
  4. Click on the Actions menu and then Publish

You will see there are other options:

  • Copy…
  • Move…
  • Delete
  • Check Out
  • Discard Check Out
  • Check In
  • Publish
  • Unpublish this version

Perhaps Microsoft will revive the Site Content and Structure and give it the modern face-lift it deserves…? Vote here if you feel the same: https://sharepoint.uservoice.com/forums/329214-sites-and-collaboration/suggestions/37335316-bring-back-the-site-content-and-structure-page

SharePoint: Content and Structure Report for All Checked Out Files

Ever wondered why a file or page was not showing up in search or did not updated during a deployment? Well perhaps it was because the “creator” had not checked-in their file or published the page…

SharePoint has a useful page called Site Content and Structure which can be used to review the following out-of-the-box reports:

  • Checked Out To Me
  • Last Modified By Me
  • Pending Approval
  • My Tasks
  • All Draft Documents
  • Going Live Within Next Seven Days
  • Expiring Within Next Seven Days

The link to the Content and structure page can be found on a Publishing site’s Site Settings page.

What if however the file was check-out by someone else? Then an answer is to create your own report and here is how to do it.

Creating a Custom Report Definition

  1. Navigate to your Publishing site collection
  2. Click Site Settings, under the SharePoint Cog menu
  3. Navigate to the hidden Reports List, to create a custom report
    http://<Tenant>.sharepoint.com/Reports%20List/AllItems.aspx
  4. Click new item and enter the following
    • Report Title: All Checked Out Files
    • Resource Id: SmtAllCheckOutUser
    • SmtCheckOutUser: SmtAllCheckedOutReportDescription
    • CAML List Type:
    • CAML Query: <Where><Geq><FieldRef Name=’CheckoutUser’ LookupId=’TRUE’/><Value Type=’int’>0</Value></Geq></Where>
    • Target Audiences:
    • Report Description: All documents and pages checked out in this site and subsites
  5. Click Save

Review the “All Checked Out Files” Report

  1. Navigate to your Publishing site collection
  2. Click Site Settings, under the SharePoint Cog menu
  3. Click Content and structure, under the Site Administration heading
    http://<Tenant>.sharepoint.com/_layouts/15/sitemanager.aspx
  4. Click Default View and select

One limitation you may notice that your report does not display who has checked-out a file or page. It is however simple enough to find the location an individual file or page:

  • Clicking Opening Link in New Window
  • Clicking the View Properties and hovering over the Name

Cheat Sheet: Fixing SharePoint Page Layouts containing Webpart with the same ID

I had problems upgrading a WSP containing one or more Page Layouts?
Unable to edit or update a Page Layout?

Related article: Editing SharePoint Webparts embedded within Page Layouts https://www.sjlewis.com/2015/10/15/editing-sharepoint-webparts-embedded-within-page-layouts/

  • Navigate to the site settings of the root website (within a site collection)
  • Click Master pages and page layouts and locate the Page Layouts
  • Make a note of the file name, for example: PageLayout.aspx
    Note: you will not be able to view or edit the page layout directly by clicking on the title or a menu item
  • Using one of the URL below, change the tenant and file name to create the required URL: https://tenant.sharepoint.com/_catalogs/masterpage/PageLayout.aspx?Contents=1
  • Once the Web Part Page Maintenance page has loaded, starting from the top select the duplicate webparts and then click Delete

You should now be able to complete the update or upgrade action you previously set out to do.

Cheat Sheet: Editing SharePoint Webparts embedded within Page Layouts

  • Navigate to the site settings of the root website (within a site collection)
  • Click Master pages and page layouts and locate the Page Layouts
  • Make a note of the file name, for example: PageLayout.aspx
    Note: you will not be able to view or edit the page layout directly by clicking on the title or a menu item
  • Using the example below, change the tenant and file name to create the required URL: https://tenant.sharepoint.com/_catalogs/masterpage/PageLayout.aspx?ControlMode=Edit&DisplayMode=Design
  • Enter your new URL into a browser to start editing the embedded webparts and content.

If however you see this error: “A Web Part with this ID has already been added to this page” then take a look at this post first: https://www.sjlewis.com/2015/11/18/fixing-sharepoint-page-layouts-containing-webpart-with-the-same-id/

Example: Office 365 Video REST API & Script Editor webpart

Here is an example of how to embedding a video using a Script Editor webpart and the Office 365 Video Portal REST API within SharePoint Publishing site.

When try this example yourself, don’t forget to edit the VideoPlayer.webpart and replace the blank GUIDs.

Quick Start:

  1. Upload a video to your Office 365 Video Portal
  2. Add the VideoPlayer.js file you the root site collection Style Library under a folder called _Custom (or change the path in the webpart definition)
  3. Upload the VideoPlayer.webpart to the Web Part Gallery
  4. Edit a Webpart Page and add the “Video player” webpart
  5. Edit the webpart’s snippet and replace the “chid” and “vid” blank GUIDs

Note: To find the “chid” and “vid” values, navigate to the video to be display within the SharePoint webpart page and copy the values form the URL into Notepad and copy the relevant GUIDs. The URL should look something like this: https://{company}.sharepoint.com/portals/hub/_layouts/15/PointPublishing.aspx?app=video&p=p&chid=00000000-0000-0000-0000-000000000000&vid=00000000-0000-0000-0000-000000000000

Chrome v Internet Explorer

Chrome you get the option to view the video in full screen unfortunate this functionality is currently not available in Internet Explorer 11. However full screen is available in Edge (Microsofts new web browser) so good news for Windows 10 Users.

Virtual Machine: SharePoint failing to create a Web Application

So your Virtual Machine doesn’t quite have enough resources to create a new Web Application using Central Admin, then you have two choices PowerShell or the workaround I’m going to describe today.

Before I describe the workaround let me describe why you might be here in the first place. Normally you would open SharePoint 2013 Central Administration and from the home page click on “Manage web applications”. At this point you click the “New” button, fill out the form and wait. If you are unlucky then you will see the “Something went wrong” screen. Unfortunately SharePoint has probably created a Content Database, an IIS Application Pool and an empty IIS Site. If so then you can try the deleting the assets using the GUI however it will almost certainly fail. Or just run the following PowerShell (and be patient):

Remove-SPWebApplication http://sitename -Confirm -DeleteIISSite -RemoveContentDatabases

The workaround:

Open the Internet Information Services (IIS) Manager window, right click on Application Pools node, select “Add Application Pool…”, enter a name (e.g. “SharePoint – site.domain.com”) and click OK.

One your new Application Pool has been created select it and click on “Advanced Settings…” (on the right, under Actions). And then follow these actions:

  1. Change the Identity to be an AD account
  2. Change Idle Time-out (minutes) from 20 to 0
  3. Change the values for the following properties to 420:
    • Ping Maximum Response Time (seconds)
    • Shutdown Time Limit (seconds)
    • Startup Time Limit (seconds)
  4. Click OK

Now you are ready to create you Web Application using SharePoint 2013 Central Administration. Navigate to “Manage web applications” and click the “New” button. Fill out the form, but this time select your new Application Pool before clicking OK and wait. Assuming all went OK then open the IIS Manager window and navigate back your new Application Pool’s Advanced Settings and change the values for the following properties back to 90:

  • Ping Maximum Response Time (seconds)
  • Shutdown Time Limit (seconds)
  • Startup Time Limit (seconds)

Job done.​

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