如何在 GAS 中测试触发功能? [英] How can I test a trigger function in GAS?

查看:11
本文介绍了如何在 GAS 中测试触发功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google Apps 脚本支持触发器,通过事件 以触发功能.不幸的是,开发环境将允许您在不传递参数的情况下测试函数,因此您无法以这种方式模拟事件.如果您尝试,您会收到如下错误:

Google Apps Script supports Triggers, that pass Events to trigger functions. Unfortunately, the development environment will let you test functions with no parameter passing, so you cannot simulate an event that way. If you try, you get an error like:

ReferenceError: 'e' 未定义.

ReferenceError: 'e' is not defined.

TypeError: 无法从 undefined 读取属性 *...*

TypeError: Cannot read property *...* from undefined

(其中 e 未定义)

可以将事件视为可选参数,并使用 是否有更好的方法在 JavaScript 中执行可选函数参数?.但这会带来一种风险,即懒惰的程序员(如果是你,请举手!)会将代码抛在脑后,并带来意想不到的副作用.

One could treat the event like an optional parameter, and insert a default value into the trigger function using any of the techniques from Is there a better way to do optional function parameters in JavaScript?. But that introduces a risk that a lazy programmer (hands up if that's you!) will leave that code behind, with unintended side effects.

当然有更好的方法吗?

推荐答案

您可以编写一个测试函数,将模拟事件传递给您的触发器函数.这是一个测试 onEdit() 触发器函数的示例.它传递一个事件对象,其中包含在 了解事件 中为电子表格编辑事件"描述的所有信息.

You can write a test function that passes a simulated event to your trigger function. Here's an example that tests an onEdit() trigger function. It passes an event object with all the information described for "Spreadsheet Edit Events" in Understanding Events.

要使用它,请在目标 onEdit 函数中设置断点,选择函数 test_onEdit 并点击 Debug.

To use it, set your breakpoint in your target onEdit function, select function test_onEdit and hit Debug.

/**
 * Test function for onEdit. Passes an event object to simulate an edit to
 * a cell in a spreadsheet.
 *
 * Check for updates: https://stackoverflow.com/a/16089067/1677912
 *
 * See https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events
 */
function test_onEdit() {
  onEdit({
    user : Session.getActiveUser().getEmail(),
    source : SpreadsheetApp.getActiveSpreadsheet(),
    range : SpreadsheetApp.getActiveSpreadsheet().getActiveCell(),
    value : SpreadsheetApp.getActiveSpreadsheet().getActiveCell().getValue(),
    authMode : "LIMITED"
  });
}

如果您好奇,编写此代码是为了测试 Google 电子表格以三个单元格为条件.

If you're curious, this was written to test the onEdit function for Google Spreadsheet conditional on three cells.

这是电子表格表单提交事件的测试函数.它通过读取表单提交数据来构建其模拟事件.这最初是为 在 onFormSubmit 触发器中获取类型错误?.

Here's a test function for Spreadsheet Form Submission events. It builds its simulated event by reading form submission data. This was originally written for Getting TypeError in onFormSubmit trigger?.

/**
 * Test function for Spreadsheet Form Submit trigger functions.
 * Loops through content of sheet, creating simulated Form Submit Events.
 *
 * Check for updates: https://stackoverflow.com/a/16089067/1677912
 *
 * See https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events
 */
function test_onFormSubmit() {
  var dataRange = SpreadsheetApp.getActiveSheet().getDataRange();
  var data = dataRange.getValues();
  var headers = data[0];
  // Start at row 1, skipping headers in row 0
  for (var row=1; row < data.length; row++) {
    var e = {};
    e.values = data[row].filter(Boolean);  // filter: https://stackoverflow.com/a/19888749
    e.range = dataRange.offset(row,0,1,data[0].length);
    e.namedValues = {};
    // Loop through headers to create namedValues object
    // NOTE: all namedValues are arrays.
    for (var col=0; col<headers.length; col++) {
      e.namedValues[headers[col]] = [data[row][col]];
    }
    // Pass the simulated event to onFormSubmit
    onFormSubmit(e);
  }
}

提示

模拟事件时,注意尽可能匹配记录的事件对象.

Tips

When simulating events, take care to match the documented event objects as close as possible.

  • 如果您想验证文档,您可以记录从您的触发器函数接收到的事件.

  • If you wish to validate the documentation, you can log the received event from your trigger function.

Logger.log( JSON.stringify( e , null, 2 ) );

  • 在电子表格表单提交事件中:

  • In Spreadsheet form submission events:

    • 所有namedValues 值都是数组.
    • 时间戳是字符串,它们的格式将本地化为表单的语言环境.如果从具有默认格式* 的电子表格中读取,则它们是 Date 对象.如果您的触发器函数依赖于时间戳的字符串格式(这是一个坏主意),请注意确保正确模拟该值.
    • 如果您的电子表格中有不在表单中的列,此脚本中的技术将模拟包含这些附加值的事件",这不是您从表单提交中收到的内容.
    • 问题 4335values 数组跳过空白答案(在新表格"+新表格"中).filter(Boolean) 方法用于模拟这种行为.
    • all namedValues values are arrays.
    • Timestamps are Strings, and their format will be localized to the Form's locale. If read from a spreadsheet with default formatting*, they are Date objects. If your trigger function relies on the string format of the timestamp (which is a Bad Idea), take care to ensure you simulate the value appropriately.
    • If you've got columns in your spreadsheet that are not in your form, the technique in this script will simulate an "event" with those additional values included, which is not what you'll receive from a form submission.
    • As reported in Issue 4335, the values array skips over blank answers (in "new Forms" + "new Sheets"). The filter(Boolean) method is used to simulate this behavior.

    *格式为纯文本"的单元格会将日期保留为字符串,这不是一个好主意.

    *A cell formatted "plain text" will preserve the date as a string, and is not a Good Idea.

    这篇关于如何在 GAS 中测试触发功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆