Category Archives: JavaScript

SPFx-People-Search

SharePoint/SPFx: Returning to Webpart Development Part #4 (with React Hooks)

Recently I was asked to develop a webpart for a modern SharePoint site. My first thoughts, where do I start; I haven’t done any webpart development for years? I would like to share my journey with you over the next few posts and hope my experience will help new and returning developers along the way.

In my previous post I covered:

In this post I will cover:

This article is different to its predecessors in the series, because I have published the SPFx-People-Search webpart solution to my GuiHub repository, I will be focusing on what I have found challenging about writing this webpart with React Hooks, SPFx and Microsoft Graph.

In the previous article I created the Project Folder Structure with stub files ready to add code. So now I can focus on creating the components such as the Service and User Interface. I deliberated on where to start, creating the Service layer or UI. Deciding to start with a service class called MSGraphService.ts and its corresponding interface.

Note: I have added a data JSON file, however I have more work to do before this can be used for testing in the local workbench.

Service Layer

The MSGraphService is based upon the Service Locator pattern which I took inspiration from an old colleague Vardhaman Deshpande who wrote this article. The MSGraphService files are located here:

Having decided on this pattern and how to implement it, the other challenges I had with the Microsoft Graph API included:

Microsoft Graph User Photo

What to do with the data returned by Microsoft Graph User Photo endpoint. With the lack of documentation, the Graph Explorer is great, but it still took a bit of work to figure out what to do with “Blob Strings” …

Microsoft Graph Explorer Me/User Photo
https://developer.microsoft.com/en-us/graph/graph-explorer?request=me%2Fphoto%2F%24value&method=GET&version=v1.0

See the getUserPhoto() function located within MSGraphService.ts

User Presence

What the different User Presence options are: User may display…? Again, the Graph Explorer was a great help, it went a long way to making up for the lack of documentation.

Microsoft Graph Explorer Me/User Presence
https://developer.microsoft.com/en-us/graph/graph-explorer?request=me%2Fpresence&method=GET&version=beta

See the getUserPresence() function located within MSGraphService.ts and the implementation within ResultCard.tsx

Configure the API permissions requests

This time I can praise the documentation by Microsoft: “To consume Microsoft Graph or any other third-party REST API, you need to explicitly declare the permission requirements from an OAuth perspective in the manifest of your solution.” For more information see https://docs.microsoft.com/en-us/sharepoint/dev/spfx/use-aad-tutorial#configure-the-api-permissions-requests

And my working example of the package-solution.json can be found here: https://github.com/sionjlewis/SPFx-People-Search/blob/main/config/package-solution.json

User Interface

To keep things simple, I kept the PeopleSearchWebPart.ts webparts “main/entry” class, created by the SPFx Yeoman scaffold, pretty much “as is”. Converting this class to React Hook seemed to be more hassle that it was worth.

Using React Hooks with the SPFx framework

So unlike all the React.JS Hook Documentation, I was unable to implement a basic function, but instead I found I needed to write something similar to the following:

export const PeopleSearch: React.FunctionComponent<IPeopleSearchProps> = (props) => { 
    … 
};

Writing the Hooks

Having organised the components into a Project Folder Structure, I started at the top:

  1. Added references and initiated object to PeopleSearchWebPart.ts and passed them on to PeopleSearch.tsx
  2. Updated the IPeopleSearchProps.tsx interface and added each of the “Wrapper” Hooks to the return statement
  3. Focusing on the ResultWrapper, I added the “useState” and “useEffect” Hooks to handle the getFilteredUsersExpanded() data, which I then “mapped” instances of the ResultCard.tsx
  4. Before focusing on details such as User Presence and User Photo, I output the “raw” User data to the user interface from the return statement. I used this technique to confirm that the service layer was connecting to and returning the data as expected

I continued on with this process of working until I “finished” the Results components and then moved onto the Footer and Search components.

You may have noticed that I have not started on the filter components as my strategy is to get something working as quickly as possible, with the following goals:

  • Enables demos and feedback loop to start earlier
  • Test the API(s) to confirm that they work as expected (or documented) and update our strategy if they don’t

Other Stuff

underscore.js vs Lodash

Back in my “JavaScript” days I was a big fan of underscore.js, so I tried it within this project, however I found the library too cumbersome to import and so I ended up replacing it with Lodash which seems to play better with TypeScript.

Conclusion

I am now a self-confessed fan of React Hooks and have really enjoyed the process of building this webpart. As with any new development technique or process, I will find better ways of doing things as I do more, but I like how clean the code looks and reckon the modularity will make the solution so much easier to support.

Siôn Lewis

28/11/2020

When attempting to debug a recently copied SPFx solution I kept seeing the following error displayed by my browser:

Cannot GET /temp/workbench.html

As per usual, I had entered the following command into the VSCode Terminal window:

gulp serve --nobrowser

Selected the Local workbench profile and clicked on Start Debugging, which attempted to opened the following URL with Google Chrome:

https://localhost:4321/temp/workbench.html

The solution to stop this “Cannot GET” error was to enter the following URL:

https://localhost:5432/workbench

This appears to reset the “service, cache or something” causing the error to go away.

Now I can debug as per normal again.

SharePoint/SPFx: Returning to Webpart Development Part #3 (with React Hooks)

Recently I was asked to develop a webpart for a modern SharePoint site. My first thoughts were; where do I start; I haven’t done any webpart development for years? I would like to share my journey with you over the next few posts and hope my experience will help new and returning developers along the way.

In my previous post I covered:

In this post I will cover:

Recommended Reading

The official React website has some fantastic documentation and to avoid duplicating what they have already published I would recommend reading the “Thinking in React” article before we move on. I found the section “Step 2: Building A Static Version In React” particularly useful to kick-off the build of this webpart.

Using React Hooks with the SPFx Framework

The first thing I did was to import the React module using following statement:

import React, { useState, useEffect } from 'react';

When I tried to build the project, I received the following error:

Module '"c:/.../SJLewis.SPFx.Webparts.People/node_modules/@types/react/index"' can only be default-imported using the 'allowSyntheticDefaultImports' flagts(1259)
index.d.ts(46, 1): This module is declared with using 'export =', and can only be used with a default import when using the  'allowSyntheticDefaultImports' flag.

Plus, the React and ReactDom import statements are underlined in red:

React and ReactDom import statement is underlined in red

What is allowSyntheticDefaultImports? It allows default imports from modules with no default export and it does not affect code emitted, it is just typechecking.

How to enable allowSyntheticDefaultImports

Open the tsconfig.json file and add the following code to the “compilerOptions” section:

"allowSyntheticDefaultImports": true

Your tsconfig.json file should look something like this:

allowSyntheticDefaultImports

And now TypeScript is happy…

React and ReactDom import statement are validated

Before moving on to the next step, let’s build the project and commit your changes to source control (just in case we break the project later).

Installing additional NPM packages

We don’t always know all of the packages we want to use upfront, however I like to add what I can upfront. For this example, I am going to add the following npm packages to my project. Enter the commands into the VS Code Terminal window:

And finish by doing some “housekeeping” and confirming that the project builds:

gulp clean
npm shrinkwrap
gulp build

Project Folder Structure

I like to start by creating a folder structure based upon the Components and Services listed within my wire-frame(s) and components list.

People Search Wire-Frame

Component List

Component NameData SourceExpected ResultsComponent Actions
Search Wrapper 
Search BoxGraph UsersZero to more itemsFilter
Search Clear Clear data & filters
Filter WrapperGraph UsersZero to more items
Filter Combo-boxGraph UsersZero to more itemsFilter
Filter Auto-suggestGraph UsersZero to more itemsFilter
Result WrapperGraph UsersZero to more items
Result CardGraph UserOne itemDisplay
Result User PhotoGraph User PhotoOne itemDisplay
Result User PresenceGraph User PresenceOne itemDisplay
Result User ContactGraph UserOne itemDisplay
Footer WrapperGraph UsersZero to more itemsDisplay

Component Folder Structures

Starting with components, add the following folders under this path:

“~\src\webparts\peopleSearch\components\”

  • filters
  • results
  • search

Next, add blank/empty .TSX files for each component:

~\src\webparts\peopleSearch\components\filters\

  • FilterWrapper.tsx
  • FilterComboBox.tsx
  • FilterAutoSuggest.tsx

~\src\webparts\peopleSearch\components\footer\

  • FooterWrapper.tsx

~\src\webparts\peopleSearch\components\results\

  • ResultWrapper.tsx
  • ResultCard.tsx
  • ResultUserPhoto.tsx
  • ResultUsrPresence.tsx      Not required / built into Persona (Office UI Fabric) control
  • ResultUserContact.tsx

~\src\webparts\peopleSearch\components\search\

  • SearchWrapper.tsx
  • SearchBox.tsx
  • SearchClear.tsx

Even thought these files are empty the project should build without any issues, I still like to build the project after every major change I make.

<em>gulp build</em>

Note: “~\” represents the project’s root folder.

Service, Models & Data Folder Structures

I am going to create the folder structure which will be used by the Service, Models & Data files. Start by adding the following folders under this path: “~\src\”

  • data
  • models
  • services

I have not planned exactly what will be created, but here is an overview as to what will go where:

  • The Data folder will contain .JSON files, these will contain mock data for testing the webpart using the local work bench
  • The Models folder will contain .TS files, which will describe the structure of the data respective of where it is stored or accesses from.
  • The Service folder will contain .TS files and classes that will represent the services and will retrieve data either from the mock or live data sources.

Next Steps

Now that I have my project structure laid out, I can focus on creating either the Data & Services or the Components & User Interface. Neither option is wrong, however, because I know more about the User Interface than the Services, that is where I will begin for my next post.

Tip: If you cannot decide on which order to build your webpart(s) take a look at the “Thinking in React” article, you may also find the section “Step 2: Building A Static Version In React” useful.

People-Search Wire Frame Page3

SharePoint/SPFx: Returning to Webpart Development Part #2

Recently I was asked to develop a webpart for a modern SharePoint site. My first thoughts were; where do I start, I haven’t done any webpart development for years? I would like to share my journey with you over the next few posts and hope my experience will help new and returning developers along the way.

In my previous post I covered:

In this post I will cover:

Avoiding Pitfalls Part #1

Let’s start by addressing the pitfalls I listed in my last post:

1. Distracted by someone else’s code

This one is easy; we are going create a new / blank project. If we need to refer to someone elses code for inspiration, then we will do this outside of our project.

2. Getting bogged down in detail

The React website has a great article on this called Thinking in React which I recommend reading. So, let’s practice what we preach….

3. Avoid the muddying of data and presentation code/layers

Well the plan we made to avoid the previous pitfall will also help with this too. If we are still confused it is because we need to do some more planning… 😊

4. Check the SPFx Project Generator Version

The tooling used to scaffold SPFx project is out of date. This should not be a problem if you have just configured a new brand environment/machine. If, however like me you are coming back to an existing environment/machine then I would recommend uninstalling everything SPFx related:

npm uninstall @microsoft/generator-sharepoint --global
npm uninstall yo --global
npm uninstall gulp --global

And finally, Node.js using the “Add or remove programmes…” to check the version and uninstall if required.

Once done, you can re-install the tools with confidence…

Solution Design (Avoiding Pitfalls Part #2)

Let’s start by creating a wire-frame, which essentially is a design without branding or colours. There are many great tools on the market for creating wire-frames, such as Balsamiq, Lucidchart or Microsoft Visio. However for this example, I am going to use Microsoft PowerPoint to demonstrate how easy it is to create an effective wire-frame. Click here to open my People-Search-Wire-Frame.pdf file.

Wire-Frames

Start by adding the components to the diagram, while thinking about how the end-user would interact with your webpart.

People Search Wire Frame Page 1

On the next diagram I have labelled each control, giving a brief description of each control and / or its behaviour. If you are a solo developer you may decide to skip this detail, however, I find the validation process useful.

People Search Wire Frame Page 2

The last page/diagram breaks the webpart down into components. I have done this by functionality, repeatability and in some cases, where the data will come from.

People Search Wire Frame Page 3

Data Sources

Now that I have a design I can start thinking about where the data is going to come from. In the past I may have used SharePoint Search with the User Profile Service, however today I am going to use the Microsoft Graph API, as “The Graph” combines multiple Microsoft 365 services into a single endpoint.

Tip: The Graph Explorer is a great place to start working Microsoft Graph, it has a number of sample queries to run against dummy data or better still sign in to your Microsoft 365 Tenant and test queries against your own data (see my next tip).

Tip: Sign-up to the Microsoft Developer Programme and get a Microsoft 365 developer subscription to develop your solutions independent of your production environment.

The table below lists the components I expect to build, obviously this may change if I find other complexities once the build is under way, plus:

  • The Data Source gives a rough idea as to where to find the data.
  • The Expected Results gives a rough idea of shape of the data.
  • The Component Action describes what the component will do with the data.
Component NameData SourceExpected ResultsComponent Actions
Search Wrapper
Search BoxGraph UsersZero to more itemsFilter
Search ClearClear data & filters
Filter WrapperGraph UsersZero to more items
Filter Combo-boxGraph UsersZero to more itemsFilter
Filter Auto-suggestGraph UsersZero to more itemsFilter
Result WrapperGraph UsersZero to more items
Result CardGraph UserOne itemDisplay
Result User PhotoGraph User PhotoOne itemDisplay
Result User PresenceGraph User PresenceOne itemDisplay
Result User ContactGraph UserOne itemDisplay
Footer WrapperGraph UsersZero to more itemsDisplay
Components List

Choosing a Framework

Just because you are developing a SPFx webpart does not mean you have to build it in React, there are other options, such as “No JavaScript framework” (i.e. hand-rolled or do it yourself) or Angular.

Sorry to disappoint, however I am going to stick with React – React Hooks possibly with useReducer.

Creating a SPFx Project

To help you reproduce my solution I have listed the steps below.

Creating a VS Code Workspace

I am a fan of Workspaces they enable you to save and share preferences including UK/NZ spellings…

  1. Create your project directory, for example:
    C:\…\Company.SPFx.Webparts.People
  2. Open Visual Studio and navigate to: File -> Open folder…
  3. Next locate and open your new directory
  4. Once opened navigate to: File -> Save Workspace As…
  5. Navigate up a folder, enter “Company.SPFx.Webparts.People.code-workspace” and click save

Scaffold the SPFx Project

Now we are ready to open the Terminal window with VS Code and run the Yeoman SharePoint generator.

  1. Open Terminal: [Ctrl]+[`]
  2. Enter the following commands:
yo @microsoft/sharepoint
  1. Next enter: MS-Graph People Search – Press enter
  2. Select: SharePoint Online only (latest) – press enter
  3. Use the current folder – press enter
  4. Do you want to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without running any feature deployment or adding apps in sites? – Y
  5. Will the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant? N
  6. Select: WebPart – press enter
  7. What is your Web part name? People Search – press enter
  8. What is your Web part description? Search for people within your organisation using Microsoft Graph – press enter
  9. Select: React – press enter

Once the Yeoman command has completed, we can check the solution by running the following commands:

gulp clean
gulp build
npm shrinkwrap
gulp serve

Source Control

I am going to designate source control out of scope for this post, however what I would recommend committing your code (or backing it up) at this point, so that you have a place you can rollback to if it all goes wrong.

Next time

For my next post I will focus on building the structure of my webpart.

SharePoint/SPFx: Returning to Webpart Development Part #1

Recently I was asked to develop a webpart for a modern SharePoint site. My first thoughts were; where do I start, I haven’t done any webpart development for years? I would like to share my journey with you over the next few posts and hope my experience will help new and returning developers along the way.

Development Environment & Tools

Development Tools

Code Editor or Integrated Development Environment (IDE).

If you have not done so already, install your preferred Integrated development environment (IDE). My choice is Visual Studio Code, however there are three supported code editors:

Now you are ready to install or in my case update the development toolchain prerequisites. Pop back to the Microsoft article and follow the steps.

Tip: Hold [Ctrl]+[`] will open the Terminal window in VS Code.

Set up your SharePoint Framework development environment

In my opinion Microsoft has done a good job in publishing a collection of articles describing how to build and deploy your first webpart. I would recommend starting by reading the “Set up your SharePoint Framework development environment” articles to get yourself up and running

Tips:

  1. At the time of writing this article, the SPFx Framework does not support the latest TLS (long term support) version of Node.js. Installing the wrong version will cause you headaches, so read “Important” notes under the Install Node.js section before you install Node.js
  2. Click here to navigate the Node.js v10.x, use the Node.js > Downloads > Previous Releases page.

Already have Node.js installed?

As a Windows 10 user, I opened “Add or remove programs” and entered Node into “Search this list” and checked the version before running executing the node-v10.22.0-x64.msi file.

The following command can be used to check the version installed:

node -v

Trusting the self-signed developer certificate

Don’t forget to configure a self-signed SSL certificate which can be done by running the following command.

gulp trust-dev-cert

You will use this when testing your custom solutions from your development environment which uses HTTPS by default.

Modern Browsers

Even though Google Chrome  is my preferred browser, I like to have Microsoft Edge and Firefox installed for additional testing capabilities.

Tip: I use Google Chrome’s persons (profiles) to switch between Tenants and Accounts. I understand that other browsers now include similar functionality.

Other Tools

Notepad++

I like this code editor for its simplicity and Plugins, such as: JSON Viewer and XML Tools.

Fiddler

Captures all HTTP(S) traffic between your computer and the Internet with Fiddler HTTP(S) proxy. Inspect traffic, set breakpoints, and fiddle with requests & responses.

Postman

Helps you build, connect and test APIs. An example is testing the Microsoft Graph API.

VS Code Extensions

Focused on SPFx development:

  • Debugger for Chrome
  • Debugger for FireFox
  • Debugger for Microsoft Edge
  • ESLint
  • jshint
  • Markdownlint
  • React Native Tools

For Source control:

  • Git Merger
  • GitLens

General Development:

  • Azure Account
  • Azure Functions
  • Azure Repos
  • Beautify
  • C#
  • Code Spell Checker
  • Edit CSV
  • Paste JSON as Code
  • PowerShell
  • Rainbow CSV

Frameworks & Fashion

Back in the mid 2010’s I built a lot of SharePoint webparts and worked with numerous JavaScript frameworks including: jQuery, jQuery UI, Underscore.js, Knockout, Vie.js and experimented AngularJS.

When the SPFx framework came on the scene the “AngularJS verses React (ReactJS)” conversation was fresh. While I built a handful of SPFx Webparts and Extensions I have to acknowledge things have moved on since then…

Back to School

Even though I had done these tutorials a few years ago, I found it invaluable to do them again:

Another great place to start with is the SharePoint Framework Client-Side Web Part Samples website and check out the Getting Started page. You can either clone the GitHub repository or just explore the code online.

My Pitfalls

If you are anything like me, I would recommend avoiding the following pitfalls:

  1. Using someone else’s code may seem like a great idea, however unless it does 90% or more of what you require you may find yourself spending more time trying to understand the code rather than writing new functionality.
  2. Getting bogged down in detail; this can easily happen if like me you enjoy detail. My strategy to avoid this is to draw wire-frames and carry out research (e.g. frameworks etc) before the build officially begins.
  3. Avoid the muddying of data and presentation code/layers; this is an area I can get bogged down in, however on a positive side the cleaner the separation the easier the code is to support and maintain.
  4. Unable to upgrade frameworks. It’s not always obvious what is going on, however if you find your projects are being scaffolded with old version npm packages then try retracing your steps and uninstalling everything including Node, before reinstalling again.

Next time

For my next post I will focus on design and frameworks.

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