Hacker rocker1169
Hacker rocker1169

Reputation: 83

Unable to write unit test cases for FHIR client api calls

I hava component Componnent1 and inside the componentDidMount i am having the below code:-

const key1 = sessionStorage.getItem("key1");
    FHIR.oauth2
      .ready()
      .then((client) =>
        client.request("<url>/" + key1, {
          resolveReferences: [
          ],
          graph: true,
        })
      )
      .then((json) => {
        console.log(json);
      })
      .catch(console.error);

And I am getting this error

● renders as expected

console.error internal/process/next_tick.js:68 TypeError: client.request is not a function at _fhirclient.default.oauth2.ready.then.client (C:\Users\dbdeb\OneDrive\Desktop\patient-application\src\components\my-health-deatails.component\allergies.component\allergies.js:68:16) at process._tickCallback (internal/process/next_tick.js:68:7)

and my Test case is like:-

import { Component1} from "../component1"
import React, { Component } from "react";
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'
import FHIR from "fhirclient";
jest.mock('fhirclient', () => ({
    oauth2: {
        ready: jest.fn(() => Promise.resolve({
            client: {
                request: jest.fn(() => { return { data: null } })
            }
        }))
    }
}));
test('renders as expected', () => {
    FHIR.oauth2.ready.mockResolvedValueOnce({ data: { entry: '' } })
    render(<Component1></Component1>)
});

Upvotes: 0

Views: 508

Answers (1)

ColdFhir
ColdFhir

Reputation: 1

For those who wander across this in the future, mocking the fhirclient library is difficult because it requires a constructor first before you can access the methods on it. This works for me:

Slim code:

jest.mock('fhirclient', (() => {
  return function () {
    return {
        authorize: jest.fn((input: any) => { return input })
    }}}))

Code with debugging:

jest.mock('fhirclient', (() => {
// Returns a mock Constructor for the smart class that takes in the request/response/storage
return function (request: any, response: any, storage: any) {
    // console.log('request is ', request)
    // console.log('response is ', response)
    // console.log('storage is ', storage)
    return {
        // Returns a mock .authorize() function that receives an object and would normally use it to redirect the client
        authorize: jest.fn((input: any) => { return input })
        // authorize: jest.fn((input) => {console.log('input is ', input)})
    }}}))

Upvotes: 0

Related Questions