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
![](https://dustinminer.com/wp-content/uploads/2023/03/1-3-427x1024.png)
4.) Ensure the configuration files are as follows
![](https://dustinminer.com/wp-content/uploads/2023/03/2.png)
![](https://dustinminer.com/wp-content/uploads/2023/03/3.png)
![](https://dustinminer.com/wp-content/uploads/2023/03/4-1.png)
TypeScript code to be unit tested
![](https://dustinminer.com/wp-content/uploads/2023/03/5-1.png)
![](https://dustinminer.com/wp-content/uploads/2023/03/6-2.png)
TypeScript unit test
![](https://dustinminer.com/wp-content/uploads/2023/06/7-1.png)
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)
![](https://dustinminer.com/wp-content/uploads/2023/02/8.png)
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
![](https://dustinminer.com/wp-content/uploads/2023/03/9-1024x619.png)
![](https://dustinminer.com/wp-content/uploads/2023/02/10.png)
![](https://dustinminer.com/wp-content/uploads/2023/03/11.png)
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