Unit test for SPFx with Jest

Introduction:

I have been working on SPFx projects since long and during the development I feel component testing is more important than the deployment. Manual testing involves people and time – and it might be difficult to manage the project when the code grows.

To speed up the development process for any SPFx solution/project we should have test cases to test the component rendering which can help to develop new components and also ensures the integrity of the existing functionality. I am going to explain how to use Jest for SPFx component which dramatically speeds up the process of running your tests.

Why it is required?

  • The code is well designed with less technical depth, making it more extensible and flexible to changes.
  • If any change occurs, it can be easily testing the solution for regression in no time
  • Better way to backup the business logic within the solution against someone willing to change the code with no business knowledge and no clue how it should work.
  • Bugs can be identified earlier (before the deployment)

How it works:

We have plenty of testing frameworks available to test our SPFx code and Jest testing framework is a best fit as its very easy to setup

“Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!”

Prerequisites:

To set up a project to use Jest, will use the popular tool Enzyme by Airbnb for testing the component rendering.

There are multiple packages we need to install to run our tests for the rendering components:

  • enzyme
  • enzyme-adapter-react-16
  • jest
  • identity-obj-proxy: allows you to test SASS / LESS / CSS imports
  • react-test-renderer
  • ts-jest: TypeScript preprocessor with sourcemap support for Jest

Let’s get started:

Create SPFx Web Part

  • Open a command prompt. Create a directory for SPFx solution.
  • Navigate to the above-created directory.
  • Run the Yeoman SharePoint Generator to create and scaffold the solution.
  • Yeoman generator will present you with the wizard by asking questions about the solution to be created.
  • Once the scaffolding process is done – lock down the project dependencies version: npm shrinkwrap
  • Packages needs to install:
  • Enzyme is a set of test utilities created for React (developed by Airbnb). Enzyme makes it easy to assert, manipulate your components’ output. Run below command on the command prompt:

npm install enzyme enzyme-adapter-react-16 react-test-renderer @types/enzyme –save-dev –save-exact

  • Jest supports asserts, mocking, code coverage, coverage threshold for continuous deployment, and summary report. Run below command on the command prompt:

npm install jest jest-junit ts-jest @types/jest –save-dev –save-exact

  • identity-obj-proxy allows to test SASS / LESS / CSS imports. Run below command on the command prompt:

npm install identity-obj-proxy –save-dev –save-exact

Note: Run the following command to install all at once:

npm i enzyme enzyme-adapter-react-16 react-test-renderer @types/enzyme identity-obj-proxy jest jest-junit ts-jest @types/jest

  • Open the solution in Visual Studio code using:

code .

Configure Jest with SPFx

Open the package.json file.

Under the “Scripts” section for “test” configuration, replace “gulp test” with “jest”.

Add “jest” configuration after “devDependencies”.

Add/Create Tests in SPFx WebPart

If you want to write some test yourself, you will have to go through a couple of steps.

Open Visual Studio Code and create new folder “test” under “src\webparts\spFxJestTestWp”. Add new file called “SPFxJest.test.ts

Run Test Cases:

On the command prompt and run the below command to execute the test cases.

npm test

Note: Keep in mind to add ID for your root ‘DIV’ in SpFxJestTestWp.tsx file under render method.

i.e: <div className={ styles.spFxJestTestWp } id=”SPFxJestTest”>

This will be used in “SPFxJest.test.ts” file as :

it(‘should root web part element exists’, () => { 

        // define the css selector 

        let cssSelector: string = ‘#SPFxJestTest’; 

SPFx Application Customizer – How to change favicon on Modern SharePoint sites

January 10, 2019 Leave a comment

What is favicon?

It is an icon associated with a particular website, typically displayed in the address bar of a browser accessing the site or next to the site name in a user’s list of bookmarks.

To change the default favicon in classic SharePoint is straight forward process that basically involves a modification of the master page. For modern sites – master page modification option is not available. Though it is possible by using Application Customizers a type of SPFx Extensions.

In this article I will explain how to use SPFx Extensions – Application Customizers to modify/change favicon on modern SharePoint sites.

Note: Find more details on SharePoint Framework Extensions if you are new to SPFx.

Let’s get started by creating a new extension project

  • Create a folder with the name of the project (i.e.SPFavIcon)
  • Type the command yo @microsoft/sharepoint

1

  • When prompted provide the necessary information as below:

2

  • It will take some time to download necessary files and prompt you with successful message like:

3

  • Open the project in Visual Studio code editor using code . command (you can use other code editor as well). Project structure for extensions and Client Side Web Parts are same apart from few additional folders.

4

Type code . to open the project (this will open visual studio code but you can use another editor). The structure of the extension project is like the SPFx web parts projects.

Update the code

  • Open ts the file is located under src–>extensions–>SpFavIcon

5.png

  • OnInit method is responsible to change the fav icon for the site. Locate OnInit method and replace the original code by the code below:

6.png

  • To add your custom variable which can store path for your fav icon URL – add new variable (or use out of the box available variable name ‘testMessage’) “favicon:string” as below:

7

  • To add the icon path – open an element.xml file from folder SharePoint>assets>xml–>CustomAction

8.png

Note: I have used SiteAssets library for this solution.

Execute/run/debug an extension project

  • Use command gulp serve –nobrowser to compile the code.

9.png

  • To test an extension, we need an id of the solution. Go to the src folder–>Open {xxxx}manifest.json and copy the id

10.png

  • Go to your modern page and add the following query string to the URL. (Note: Replace id by your solution id value)

11.png

  • Choose load debug scripts
  • Your new favicon on your browser tab is available

favicongif

Package the Solution

  • Run gulp bundle –ship command to package the solution
  • Run gulp package-solution –ship to get the installation package of the solution
  • This will create solution folder under sharepoint and *.sppkg file will be available.

12

  • Drag & Drop or upload the package file to app catalog.

13.png

Hope this helps you!!!.

SharePoint Framework Extensions – Part 2 (Application Customizers)

If you want to learn about What is SPFx Extension

Before exploring each Extensions in depth, let me explain little bit about the development and debugging experience.

Yeoman SPFx generator:

Like other SharePoint Framework customization component, you are going to use the Yeoman Generator to create Extensions.

Version 1.3 of the Yeoman generator and all subsequent versions include the project scaffolding templates and dependencies that you need to create and test SharePoint Framework Extensions.

Execution requires modern experience

Extensions need a live SharePoint site and a modern page to run.

Application Customizers

This will allows you to use arbitrary JavaScript’s on all pages or to access well knwon HTML element placeholders and put your custom rendering logic there. Microsoft wants to make it possible for you to change certain elements, such as the header and footer among others, in a supported manner.

In previous versions – if you are a SharePoint developer, you might have used or remember “delegate controls”. You can compare or think of Application Customizers as delegate controls for SPFx.

Currently, Application Customizers are supported at site, Web, and list scopes.

Let’s see how to write a simple Application Customizer.

Create a new SPFx project using this command: yo @microsoft/sharepoint

Note: Here i am assuming you are familiar with how to use Node.JS to create a client side web part. If you want to learn how to create client side web part Click here.

This leads you through a wizard as below. Enter information as you want.

AppCustExt

Once your project is created, type code . to open it in VS Code.

Once your project opens, go to the src\extensions folder and locate your customizer.

Your customizer should match the name you provided when creating the solution. Please refer above screen for detail. You should see a manifest.json file which describes to SharePoint the details of your customizer (In this sample,appCustExtensions). It should look like below:

Cust1.png

In above screen, there is a GUID, the “id” field. That is an unique identifier for your customizer. Take a note of this GUID as we will need this later on.

Now, open the .ts file for your customizer. You can find it in the same folder as the manifest.json file. My .ts file can be seen as below:

DotTS.png

You can see, an Application Customizer is simply a class that inherits from BaseApplicationCustomizer. Also note that our customizations go in the “OnInit” method and not the constructor. This is because the state of the customizer isn’t available in the constructor.

Debugging Startup – Option 1 – Manual Setup

The first option is more of a manual setup – you are going to first start the local web server but don’t launch the browser. Just launch the Web Server.

You are going to do that by saying 

$ gulp serve –nobrowser

Access the following url:

https://xxx.sharepoint.com/sites/home/
loadSPFX=true&
debugManifestsFile=
https://localhost:4321/temp/manifests.js&
customActions={
“theGUIDOfYourCustomizer”:{
“location”:
“ClientSideExtension.ApplicationCustomizer”,
“properties”:
{“testMessage”:”Hello as property!”}}}

This query string tells SharePoint how to treat this debugging experience.

loadSPFX:

This is a flag that tells SharePoint to load the SharePoint Framework on the page. The SharePoint Framework is genuinely not added at every page in SharePoint unless there is a component that depends on the SharePoint Framework that’s been registered on the page. They do this for performance reasons. No need to add the JavaScript that supports SharePoint Framework if it is not needed on the page.

debugManifestsFile=https://localhost:4321/temp/manifests.js:

By default SharePoint Framework is only gonna look for Manifest file in the app catalog for things that we deployed and on the SharePoint servers for the system libraries.

What this debug manifests is going to do is – its going to tell SharePoint Framework where the local web server is and his manifest file. So they can fetch and know what the extensions are available to us and what should be loaded on the page.

And then the third section for this query string is gonna contain some specific information about our extension.

&customActions={“<COMPONENT_GUID>”:{“location”:”ClientSideExtension.ApplicationCustomizer”,”properties”:{“name”:”value”}}}

Now this is gonna differ for each type of an extensions. We look into what all options. Generally speaking its gonna tell the SharePoint Framework the id of the extension that can be loaded now or that should be loaded and tells where it supposed to go like should go into toolbar or context menu and allow some arbitrary properties as well.

Now in the browser – separate browser window – you gonna navigate to live SharePoint modern page or list in SharePoint site and you can add a special query string and then refresh the page.

Note that I’ve broken down the URL with return characters to make it easier to read. But it’s a URL, so write it in a single line. Also, the GUID mentioned above is the GUID from your manifest.json file.

Your browser should show you a dialog box, as

Debug.png

This disclaimer screen allows debug scripts to load, you’re effectively running them within the context of the page. It serves as a good warning to end-users not to load any random stuff from the Internet, while giving developers an easy way to inject and test their code. Go ahead and load debug scripts and verify that you can see the customization, as shown in below

Alert.png

Using this technique, you can run any arbitrary JavaScript on the page.

In next post I will explain how to customize Customize your Modern Sites

SharePoint Framework Extensions – Part 1 (What is SPFx Extensions)

July 2, 2018 1 comment

If you want to learn about Why SPFx has been introduced

You can use SharePoint Framework (SPFx) Extensions to extend the SharePoint user experience. With SharePoint Framework Extensions, you can customize more facets of the SharePoint experience, including notification areas, toolbars, and list data views.

You can consider – SharePoint Framework Extensions are being touted as the replacement for Custom Actions, JS Link, and more – but what are they really? Whether you’ve started experimenting with the SharePoint Framework or not, come find out exactly what the Extensions are, when to use them, limitations, and advantages.

SharePoint Framework Extensions are not only powerful and flexible tools to customize SharePoint, when it comes to modern pages, they’re the only way.

What is SharePoint Framework?

SharePoint Framework Extensions enable you to extend the SharePoint user experience within modern pages and document libraries, while using the familiar SharePoint Framework tools and libraries for client-side development.

In this series of post – I will explain How you can customize and extend the SharePoint user interface and experience with the SharePoint Framework Extension.

This customization options adding to the SharePoint Framework lately year 2017 bring some of the options available to us and previous development models that supports the classic experience to the modern experience.

History:

Extensions were not included in very first releases of SharePoint Framework.

They were released in Developer Preview to developer tenants in the version 1.1.1 on June 12, 2017

Release candidate – v1.2.0 on August 29,2017

And finally they release as General Available to all tenants in SharePoint online in version 1.3.0 on September 25, 2017

Available:

Where can we use this?

  • Extensions are available in all SharePoint online tenants.
    • Generally available in Modern sites, pages, lists and libraries
    • We are using in classic sites, pages and lists – in classic experience. We can revert to old classic user experience or modern user experience.
  • That’s also not available to us in Feature Pack 2 of SharePoint 2016 for on-premises SharePoint deployments.
    • The reason for this because like I said – this needs a modern experience.
    • Microsoft has said that the modern experience will be introduce in next SharePoint on-premises major release.

What’s Possible with Extensions:

So what’s possible with extensions and what type of extensions are available in the SharePoint Framework.

There are all parts of same fashion from things that we used to be able to do in previous SharePoint – Customization and development model.

Let me explain you brief introduction on different types of Extensions before we jump into.

Application Customizers:

This will allows you to use arbitrary JavaScript’s on all pages within a SharePoint site. It also allows to write html to some well-known placeholder element on every single page. So we can add things like say header and footer.

You might familiar with delegate controls and script link attribute control

Command Sets:

This will allow you to put buttons on the toolbar or in the context menu of item in lists and libraries. When you click on this buttons they going to run code that you have specified.

You might be familiar with old functionality  called custom actions.

Field Customizers:

This will allow you to customize the rendering of the cell within a list view of a site.

For instance, a “progress” field might be a lot more interesting as a progress bar than a number. With field customizers, you can change that number to look like a progress bar.

You might be familiar with term JSLink or CSR (Client Side Rendering) framework. This is the modern experience to those.

In next post, I will explain Application Customizers in detail

Add a second Web Part to a SPFx project

During the workshops I have organized and receiving a common question from SPFx developers on “How to add a new web part to a SPFx solution/project?”

In this post I will explain how to add a second web part to your SPFx project. Generally, when we are generating a new SharePoint Framework project using the SharePoint Yeoman generator a new web part is automatically added. But what if you wanted to add another one?

SharePoint Framework ships with a Yeoman generator that takes care of scaffolding SharePoint Framework project.

By running the generator and answering a few questions on the command prompt, the generator creates a new project for you with one Web Part built using React, Knockout or no framework at all.

Using the generator is a great and easy way to create a new project until you will want to add a new Web Part.

You have to call the SharePoint Yeoman generator on your existing SharePoint Framework project in order to add a  new Web Part to your existing SharePoint Framework project.

Note: For this post, I am adding second web part in “SPFxSolution” directory where my first web part (“WebPartOne”) is already created.

31

The Yeoman generator will identify that it is running on an existing project and instead of scaffolding the whole project it will skip directly to adding a new Web Part.

After answering the standard questions about the Web Part’s title, description and framework, the SharePoint Framework Yeoman generator will add the new Web Part to the project and will register it with the project’s configuration so that the Web Part is built into a new bundle.

Open the solution in VS Code using code . command.

32.png

You can see two different web parts in the solution along with localized resources information.

Update the text if you want – just to verify when both web parts render on page.

Run gulp serve command to add/open both the Web Parts in local workbench.

33.png

You can see two Web Parts (I have used different icons for both web parts)

34.png

Add both the Web Parts

35.png

You can see different content for both the Web Parts.

Deployment Commands:

Stop the gulp serve command execution and run gulp bundle –ship command

36.png

 

This command will help us to bundle all the typescript files and it’s dependencies from node_modules into a single JavaScript compiled file.

Initially, the compiled typescript files are converted into JavaScript files and saved in lib folder and then from there the final bundle file will be saved in a folder called temp/deploy.

Now execute gulp package-solution –ship

This command will help us build the installation file with an extension .sppkg file.

Once you run this command .sppkg file will be created in the SharePoint folder under the project directory and the bundle file which has been generated after executing the command

Deployment:

To deploy the SPFx Web Parts upload the package file (.sppkg file) in App Catalog.

When you upload it to the App Catalog, you will be prompted with below popup,

37.png

Make sure to check “Make this solution available to all sites in the organization” checkbox. Click on Deploy

Add Web Parts on Page:

Now go ahead and create a modern page (or use existing page) from Site Contents and you will a get a screen like below. Click the plus icon at the center to list down the available apps that can be added to the page, where you can find your Web Part as well.

38.png

Add both the Web Parts

39.png

Publish the page – update the layout if required. Both Web Part will render like :

40.png

Conclusion:

When generating SharePoint Framework projects using the SharePoint Framework Yeoman generator, it automatically adds one Web Part to the project. You can easily add a new Web Part by re-running the generator on the existing project.

I’m speaking at Collab365 Global Conference Nov 2

October 23, 2017 Leave a comment

CollabImage

Have you heard about the virtual Collab365 Global Conference 2017 that’s streaming online November 1st – 2nd?

Join me and 120 other speakers from around the world who will be bringing you the very latest content around SharePoint, Office 365, Flow, PowerApps, Azure, OneDrive for Business and of course the increasingly popular Microsoft Teams. The event is produced by the Collab365 Community and is entirely free to attend.

Places are limited to 5000 so be quick and register now.

During the conference I’d love you to watch my session which is called : ‘SPFx – A modern development model for SharePoint’

SharePoint Framework (SPFx) promoted as “the future of SharePoint development” has been released in developer preview. The framework might be new, but that is a framework that we all have been longing for quite some time. Client-side development has been here for years and we all built our own frameworks. This model leverages techniques we are used to such as CSOM, the SharePoint REST API’s, the Microsoft Graph etc. and at the same time embraces open source technologies such as node.js, Gulp, Yeoman and more. I will talk about SharePoint Development Model Evolution and demonstrate use of Light Weight Components with SPFx by developing client side Web Parts

If you join me, you will learn:

  • What is SPFx and Why it has been introduced
  • How to use different tool chains and libraries
  • How to create client-side web parts
  • How to deploy/publish on O365 Tenant
  • How to deploy on Azure CDN
  • How to use the web parts on Modern pages

Topic(s):

  • SharePoint

Time (in UTC) :

  • Thursday, November 2 2017 12:00 PM

How to attend :

  1. Register here.
  2. At the time listed above go here to watch my session. (you can also add me to your own personal planner from the agenda.
  3. Be ready to take notes!
Categories: SharePoint 2016, SPFx

SharePoint Framework – A modern development model for SharePoint

SharePoint Framework (SPFx) promoted as “the future of SharePoint development” has been released in developer preview. The framework might be new, but that is a framework that we all has been longing for quite some time. Client-side development has been here for years and we all built our own frameworks. Now Microsoft is creating this framework for us, it is standardized and they will also build in native support for this framework in SharePoint. This model leverages techniques we are used to such as CSOM, the SharePoint REST API’s, the Microsoft Graph etc and at the same time embraces open source technologies such as node.js, Gulp, Yeoman and more.

I will explain about using Light Weight Components with SPFx, developing client side Web Parts along with other demos.

 

Categories: SharePoint, SPFx