jest: mock response in googleapis NodeJS library


I’m trying to mock the response from a nested method in the googleapis NodeJS client library.

My actual code:

const { google } = require("googleapis");

const directory = google.admin("directory_v1");

const apiResponse = await directory.users
  .get({
    userKey: email,
  })
  .catch((e) => {
    // "Not Found" (user isn't in managed)
    if (e.response.status === 404) {
      managedStatus = "NOT_MANAGED";
      return e.response;
    }

    // Unknown errors
    const msg = "Unhandled response from Directory API";
    throw new Error(msg);
  });

// Successful case, check if user account is suspended or archived
if (apiResponse.status === 200) {
  if (apiResponse.data.suspended || apiResponse.data.archived) {
    managedStatus = "DEACTIVATED";
  } else {
    managedStatus = "MANAGED";
  }
}

My attempted test:

const { google } = require('googleapis')
const { checkAccountType } = require('../accountType')
jest.mock('googleapis')


test('test mocks', async () => {

const accountType = await checkAccountType('[email protected]')

)}

What I get now when running jest:

    TypeError: Cannot read property 'users' of undefined

      69 |   let managedStatus
      70 |
    > 71 |   const apiResponse = await directory.users
         |                                       ^
      72 |     .get({
      73 |       userKey: email,
      74 |     })

If i try something crude like:


const directory = google.admin('directory_v1')
directory.users.get.mockResolvedValue('test')

I get:

   TypeError: Cannot read property 'users' of undefined

      53 |     //const mockMakeKey = jest.fn(() => 'mock-key')
      54 |     const directory = google.admin('directory_v1')
    > 55 |     directory.users.get.mockResolvedValue('test')
         |               ^
      56 |     const accountType = await checkAccountType('[email protected]')
      57 |     console.log(accountType)
      58 |   })

Essentially, I want to mock various returns/errors so I can validate my functions logic.

Thanks for your help!

Source: JavaSript – Stack Overflow

November 20, 2021
Category : News
Tags: google-api-nodejs-client | javascript | jestjs | mocking | node.js

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.