Dave Clark IO

Unit test your client-side customisations even faster

xrm-mock has been used across several projects both by myself and others, and has received some useful feedback.

Sep 14th 2017ยท3 min read
fast cyclists

Last month I released this post detailing how you can unit test your JavaScript customisations for Dynamics 365.

In summary, xrm-mock is an npm package which you can install to mock the Xrm object in your client-side code. By mocking Xrm, you can write tests to assert the state of your CRM forms after JavaScript functions are called, such as onLoad() and onChange() for a field.

xrm-mock has been used across several projects both by myself and others, and has subsequently received some useful feedback. Namely:

"mocking Xrm is hard"

...and not to mention time consuming.

Enter: xrm-mock-generator. This project drastically reduces the time it takes to mock your CRM form's Xrm object. A usage guide is available on the project's GitHub page (link here), but here it is again:

  • Step 1: install via npm install xrm-mock-generator
  • Step 2: import var XrmMockGenerator = require("xrm-mock-generator");
  • Step 3: initialise a global Xrm object var Xrm = XrmMockGenerator.initialise();
You now have a global Xrm object, as if you had loaded a form in CRM.

Here's an example:

This example showcases a contact form that changes the contact's firstname from Joe to Bob when the form is loaded.

src/contact.js

(function() {
  "use strict";

  var Contact = () => {};

  Contact.prototype.onLoad = function() {
    Xrm.Page.getAttribute("firstname").setValue("Bob");
  };

  // node
  module.exports = new Contact();

  // browser
  global.Contact = new Contact();
})();

test/contact.test.js

describe("Contact Form", () => {
  var XrmMockGenerator = require("xrm-mock-generator");
  var ContactForm = require("../src/contact.js");

  beforeEach(() => {
    XrmMockGenerator.initialise();
    XrmMockGenerator.createString("firstname", "Joe");
  });

  describe("default", () => {
    expect(Xrm.Page.getAttribute("firstname").getValue()).toBe("Joe"); //true
  });

  describe("onLoad", () => {
    ContactForm.onLoad();

    expect(Xrm.Page.getAttribute("firstname").getValue()).toBe("Bob"); //true
  });
});

You'll notice the line: XrmMockGenerator.createString("firstname", "Joe"); - that's how you add an attribute to Xrm. You can also add date attributes, option sets etc. which is all detailed on the GitHub usage guide.

The next primary goal of the project is to automate attribute metadata. That is: connect to a CRM organisation and automatically download the metadata for a form. If you feel like you can contribute or offer a suggestion, please message me on GitHub.

Dave Clark IO
AboutLinkedInTwitterGitHub