You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试含可抛出异常初始化函数的对象(QUnit+Google Apps Script)

Testing Exception-Throwing Logic in Google Apps Script with QUnit

Got it, let's tackle this. The problem you're hitting is that your setup callback is triggering an exception before your tests can even execute. Since setup runs before every test case, any uncaught error there will fail all your tests immediately. Instead, you need to move the logic that might throw an exception into your individual test cases and use QUnit's throws assertion to validate that the error is thrown as expected.

Here's how to refactor your tests properly:

1. Move Error-Prone Logic Out of Setup

First, stop calling sortColumns (or any logic that might throw) in your setup function. Reserve setup for safe, repeatable environment setup—like creating a test sheet, clearing test data, or initializing mock objects—things that shouldn't throw unless your test environment is broken.

2. Use assert.throws() to Validate Exceptions

QUnit's throws assertion is designed specifically for testing functions that should throw errors under certain conditions. It lets you define:

  • The function to execute that should throw
  • The expected error (can be an Error object, string, or regex pattern)
  • A message to describe the assertion

Example Test for Missing Keyword

Let's assume your sortColumns function looks something like this (searching for a keyword in sheet headers):

function sortColumns(sheet, targetKeyword) {
  const headerRow = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
  const columnIndex = headerRow.indexOf(targetKeyword);
  
  if (columnIndex === -1) {
    throw new Error(`Keyword "${targetKeyword}" not found in sheet columns`);
  }
  
  // Rest of your sorting logic...
}

Your test case would then look like this:

QUnit.test('sortColumns throws error when keyword is missing', function(assert) {
  // Get a test sheet (use a dedicated test sheet in your spreadsheet)
  const testSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test_Sheet');
  
  // Use assert.throws to verify the exception is thrown
  assert.throws(
    // Wrap the function call in an anonymous function
    () => sortColumns(testSheet, 'NonExistent_Keyword'),
    // Match the expected error message (can use regex for flexibility)
    /Keyword "NonExistent_Keyword" not found/,
    'Should throw an error when the target keyword is missing from columns'
  );
});

QUnit.test('sortColumns runs without error when keyword exists', function(assert) {
  const testSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test_Sheet');
  
  // Verify no exception is thrown by wrapping the call in assert.ok
  assert.ok(
    () => sortColumns(testSheet, 'Existing_Keyword'),
    'Should not throw an error when the target keyword exists'
  );
  
  // Add additional assertions here to validate the sorting behavior, e.g.:
  // const sortedData = testSheet.getRange(2, 1, testSheet.getLastRow()-1, 3).getValues();
  // assert.deepEqual(sortedData, expectedSortedData, 'Columns should be sorted correctly');
});

3. (Optional) Use Mock Objects for Isolation

To avoid relying on a real spreadsheet (which can make tests slower or flaky), you can mock the Sheet object to simulate missing or existing keywords. This lets you run tests without needing a live Google Sheets environment:

QUnit.test('sortColumns throws error with mocked sheet (no keyword)', function(assert) {
  // Mock a sheet with headers that don't include our target keyword
  const mockSheet = {
    getLastColumn: () => 3,
    getRange: () => ({
      getValues: () => [['Name', 'Age', 'Email']]
    })
  };
  
  assert.throws(
    () => sortColumns(mockSheet, 'Address'),
    /Keyword "Address" not found/,
    'Throws error for missing keyword in mocked sheet'
  );
});

Key Takeaways

  • Keep setup focused on safe environment prep, not business logic that might throw.
  • Use assert.throws() to explicitly test that exceptions are thrown when expected.
  • Consider mocking Google Apps Script objects to isolate your tests from the live spreadsheet environment.

内容的提问来源于stack exchange,提问作者Mike Warren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:12:05