camelCaseDave / xrm-mock

:books: A fake implementation of the Xrm object model. Written in TypeScript against @types/xrm definitions.
MIT License
79 stars 31 forks source link

How to properly use Form Context? #58

Closed ddelic043 closed 4 years ago

ddelic043 commented 4 years ago

We are using Event and Form Context in our forms, and when writing tests with xrm-mock, the changes that are done in the code are then not reflected in the test.

Here is the test result: Expected: "Notes (2)" Received: "Notes"

This is how my test looks like:

import { XrmMockGenerator }  from "xrm-mock"
import account from "../account_main"
import * as sinon from "sinon"

describe("account", () => {
    beforeEach(() => {
      XrmMockGenerator.initialise();
    });

    it("count notes and update the label", () => {
      XrmMockGenerator.Tab.createTab("notes", "Notes", true);
      var context = XrmMockGenerator.getEventContext();

      const stub = sinon.stub(Xrm.WebApi, "retrieveMultipleRecords").resolves({
        entities: ["1", "2"],
        nextLink: null
      });

      account.showAttachmentCount(context);

      let tab = context.formContext.ui.tabs.get('notes');

      expect(tab.getLabel()).toBe("Notes (2)"); // Pass
    });

});

This is the function that is being tested:

static showAttachmentCount(context: Xrm.Events.EventContext) {
        const formContext = context.getFormContext();

        var filter = "?$select=subject&$filter=_objectid_value eq (" + formContext.data.entity.getId() + ")";

        Xrm.WebApi.retrieveMultipleRecords("annotation", filter).then(notes => {
            if (notes.entities.length > 0) {
                var tab = formContext.ui.tabs.get('notes');

                if (tab !== null) {
                    console.log(tab.getLabel());
                    tab.setLabel(tab.getLabel() + ' (' + notes.entities.length.toString() + ')');
                }
            }
        }).catch();
    }

What am I doing wrong here? Do I need to apply the changes to the context somehow?

camelCaseDave commented 4 years ago

Hi @ddelic043

XrmMockGenerator.Tab.createTab() should push the new tab to formContext automatically, so you shouldn't have to apply changes to the context yourself.

Did you figure out why the expected result wasn't changing?