msgraph-sdk-javascript icon indicating copy to clipboard operation
msgraph-sdk-javascript copied to clipboard

I want to unit test the MicrosoftGraphClient and mock the request to the active directory in Node.js using Jest and Typescript.

Open IgorLopLego opened this issue 3 years ago • 1 comments

I am trying to mock and unit test the current class: ActiveDirectory.ts

import { Client as MicrosoftGraphClient } from "@microsoft/microsoft-graph-client/lib/src/Client";                                                             
import { ActiveDirectoryUserStatus } from "../models/ActiveDirectoryUserStatus";

export class ActiveDirectory {
  constructor(private readonly microsoftGraphClient: MicrosoftGraphClient) {}

  public async lookup(
    email: string
  ): Promise<[string, ActiveDirectoryUserStatus]> {
    const emailNickname: string = email.split("@")[0];
    const userDetails = await this.microsoftGraphClient
      .api(`/users?$search="mail:${email}" OR "mailNickname:${emailNickname}"`)
      .header("ConsistencyLevel", "eventual")
      .select([
        "accountEnabled",
        "displayName",
        "jobTitle",
        "mail",
        "mobilePhone",
        "preferredLanguage",
      ])
      .get();
    const usersJson = userDetails["value"];

    if (usersJson.length == 0) {
      return [email, ActiveDirectoryUserStatus.NotFound];
    } else if (usersJson.length == 1) {
      return [
        email,
        usersJson[0]["accountEnabled"]
          ? ActiveDirectoryUserStatus.Enabled
          : ActiveDirectoryUserStatus.Disabled,
      ];
    } else {
      return [email, ActiveDirectoryUserStatus.FoundMultipleTimes];
    }
  }
}

ActiveDirectoryUserStatus

export enum ActiveDirectoryUserStatus {
  // eslint-disable-next-line @typescript-eslint/naming-convention
  Enabled,
  NotFound,
  Disabled,
  FoundMultipleTimes,
}

Could you provide an example of how you would mock this request?

IgorLopLego avatar Aug 10 '22 13:08 IgorLopLego

@IgorLopLego You can try out the ChaosHandler.ts provided by the Graph JavaScript library and plug it in the middleware to mock the request.

Example: https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/9441382f7963fa782cd30a103af2632d7585e0a0/test/development/workload/PageIterator.ts#L116

nikithauc avatar Aug 12 '22 06:08 nikithauc

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment.

ghost avatar Aug 16 '22 08:08 ghost