Unit testing with xrm-mock in Visual Studio 2022

Overview

The purpose of this post is to provide an introduction into how to setup automated unit testing of Dynamics 365 client-side TypeScript.

Initial Install & Setup

1.) Install node.js if not already installed (for npm & package.json support)

2.) Create a project (such as a ‘Blank Node.js Console Application’ project) with the name ‘WebResources’

3.) Install the following npm packages (either via the Solution Explorer or the terminal window) displayed in Figure 1

Figure 1

4.) Ensure the configuration files are as follows

Figure 2 – jest.config.js
Figure 3 – package.json
Figure 4 – tsconfig.json

TypeScript code to be unit tested

Figure 5 – cpl_common.ts
Figure 6 – InitialInterviewForm.ts

TypeScript unit test

Figure 7 – InitialInterviewForm_test.ts

Referring to Figure 7, mock attributes cpl_conditionsoforder, cpl_otherconditionsoforder, cpl_explainconditionsoforder & cpl_explainotherconditionsoforder are created. These need to be created because they are referenced in the function being tested (Figure 5)

Figure 8

Referring to Figure 8, to learn the syntax for creating xrm-mock test cases, I would recommend looking at these pages

Executing the unit tests

Figure 9 – the project’s properties
Figure 10
Figure 11

Referring to Figure 11, note that console.info debug statements will be displayed here

Appendix

npm packages

@types/jest – TypeScript definitions for jest. Without this, words such as ‘describe’ wouldn’t resolve (Figure 7)

@types/node – TypeScript definitions for Node. js

jest – A JavaScript testing framework designed to ensure correctness of any JavaScript codebase

ts-jest – A TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript

typescript – A TypeScript is a language for application scale JavaScript development

xrm-mock – A fake implementation of the Dynamics 365 Client API and Xrm object model