如何模拟在函数外部实例化的oauth2客户端?

问题描述 投票:0回答:1

我有一个正在尝试测试的文件 - apiCallout.js。这是粗略的结构。


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


const GOOGLE_CALENDAR_CLIENT_ID = process.env.BOOKIT_GOOGLE_CLIENT_ID;
const GOOGLE_CALENDAR_CLIENT_SECRET = process.env.BOOKIT_GOOGLE_CLIENT_SECRET;
const instanceURL = process.env.APP_BASE_URL || 'http://localhost:5000';


const oauth2Client = new google.auth.OAuth2(
  GOOGLE_CALENDAR_CLIENT_ID,
  GOOGLE_CALENDAR_CLIENT_SECRET,
  instanceURL + '/googleRedirect'
);

function generateOAuthLink(){
  const authorizationUrl = oauth2Client.generateAuthUrl({
    // 'online' (default) or 'offline' (gets refresh_token)
    access_type: 'offline',
    /** Pass in the scopes array defined above.
     * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
    scope: scopes,
    // Enable incremental authorization. Recommended as a best practice.
    include_granted_scopes: true
  });
  return authorizationUrl;
}

这是我的测试文件。 apiCallout.test.ts

import { beforeEach, describe, expect, jest, test } from '@jest/globals';

import {
  generateOAuthLink,
} from './apiCallout';

// Mock googleapis module
jest.mock('googleapis', () => ({
  google: {
    auth: {
      OAuth2: jest.fn().mockImplementation(() => ({
        setCredentials: jest.fn(),
        generateAuthUrl: jest.fn().mockReturnValue('https://mock-auth-url.com')
      }))
    },
  }
}));

describe('google.js API Functions', () => {
  beforeEach(() => {
    jest.resetAllMocks();
  });

  describe('testing generateOAuthLink()', () => {
    
    test('should return a valid OAuth link with correct parameters', () => {

      const link = generateOAuthLink();
      expect(link).toBe('https://mock-auth-url.com');
    });
  });
})

由于我的 oauth2client 是在函数外部实例化的,所以每当我在测试中运行该函数时,它实际上都会调用 google api,而不是使用模拟响应。有没有办法覆盖实例化?

node.js unit-testing jestjs google-api mocking
1个回答
0
投票

我认为你可以在函数内移动 oauth2Client :

function generateOAuthLink(){
  const oauth2Client = new google.auth.OAuth2(
    GOOGLE_CALENDAR_CLIENT_ID,
    GOOGLE_CALENDAR_CLIENT_SECRET,
    instanceURL + '/googleRedirect'
  );

  const authorizationUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: scopes,
    include_granted_scopes: true
  });
  return authorizationUrl;
}
© www.soinside.com 2019 - 2024. All rights reserved.