Test function with Apps Script for ChatGPT


Creating a test function for your Google Apps Script code involves simulating responses from the external API and the Google services without actually making requests or creating documents. This is because Google Apps Script does not support traditional unit testing frameworks or libraries directly. However, you can structure your code to simulate parts of it for testing purposes.

Here’s how you can create a test function for your existing code:

  1. Refactor the Original Functions: Refactor your functions to accept dependencies. This is a common practice for making code more testable.
  2. Create Mock Functions: These are functions that simulate the behavior of the real functions without performing actual operations.
  3. Write Test Functions: These functions will use your mock functions to test different scenarios.

Here’s an example based on your code:

// Refactored functions with dependency injection
function sendPromptToChatGPT(prompt, fetchFunction) {
  // Use fetchFunction instead of UrlFetchApp.fetch
  const response = fetchFunction('https://api.openai.com/completions', /* options */);
  const json = JSON.parse(response);
  const text = json.choices[0].text.trim();
  return text;
}

function createDocWithResponse(responseText, docApp, driveApp, folderId) {
  // Use docApp and driveApp instead of DocumentApp and DriveApp
  const doc = docApp.create('ChatGPT Response');
  const body = doc.getBody();
  body.setText(responseText);
  const file = driveApp.getFileById(doc.getId());
  driveApp.getFolderById(folderId).addFile(file);
  driveApp.getRootFolder().removeFile(file);
  return doc.getUrl();
}

// Mock functions
function mockFetch(url, options) {
  // Simulate a response from the OpenAI API
  return JSON.stringify({
    choices: [{ text: 'This is a simulated response' }]
  });
}

function mockDocumentApp() {
  // Simulate the DocumentApp behavior
  return {
    create: function (name) {
      return {
        getId: function () { return 'dummyDocId'; },
        getBody: function () { return { setText: function (text) {} }; },
        getUrl: function () { return 'http://dummyDocUrl'; }
      };
    }
  };
}

function mockDriveApp() {
  // Simulate the DriveApp behavior
  return {
    getFileById: function (id) {
      return {};
    },
    getFolderById: function (id) {
      return {
        addFile: function (file) {},
        removeFile: function (file) {}
      };
    },
    getRootFolder: function () {
      return {
        removeFile: function (file) {}
      };
    }
  };
}

// Test function
function testFunctions() {
  const dummyPrompt = 'This is a test prompt';
  const dummyFolderId = 'dummyFolderId';

  const testResponse = sendPromptToChatGPT(dummyPrompt, mockFetch);
  console.log('Test response from ChatGPT:', testResponse);

  const testDocUrl = createDocWithResponse('Test response', mockDocumentApp(), mockDriveApp(), dummyFolderId);
  console.log('Test document URL:', testDocUrl);
}

// Run this function to perform the tests
testFunctions();

/*

In this example, mockFetch, mockDocumentApp, and mockDriveApp are mock functions that simulate UrlFetchApp.fetch, DocumentApp, and DriveApp, respectively. They return fixed values instead of performing real operations. This allows you to test the behavior of sendPromptToChatGPT and createDocWithResponse without making real API calls or creating actual documents.

Please remember that this is a basic example. In real-world applications, you may need more sophisticated mocks and tests to cover different scenarios and error conditions.