如何测试气体的触发功能?

时间:2021-03-16 08:41:17

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' is not defined.

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.

可以将事件视为可选参数,并将默认值插入到触发器函数中,使用“在Javascript中是否有更好的方法来执行可选的函数参数?”但这也带来了一个风险:一个懒惰的程序员(如果是你的话,举起手来)会把代码留在后面,会带来意想不到的副作用。

Surely there are better ways?

肯定有更好的方法吗?

2 个解决方案

#1


66  

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()触发函数的示例。它通过一个事件对象,在理解事件中使用“电子表格编辑事件”所描述的所有信息。

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

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

/**
 * Test function for onEdit. Passes an event object to simulate an edit to
 * a cell in a spreadsheet.
 *
 * Check for updates: https://*.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"
  });
}

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

如果你好奇,这是为了测试谷歌电子表格的onEdit函数,条件是三个单元格。

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?.

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

/**
 * Test function for Spreadsheet Form Submit trigger functions.
 * Loops through content of sheet, creating simulated Form Submit Events.
 *
 * Check for updates: https://*.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://*.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:

    电子表格提交事件:

    • all namedValues values are arrays.
    • 所有的namedValues值都是数组。
    • 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.
    • 正如第4335期所述,值数组跳过空白答案(在“新表单”+“新表单”中)。使用filter(Boolean)方法来模拟这种行为。

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

*一个格式为“纯文本”的单元格将把日期保存为字符串,这不是一个好主意。

#2


2  

2017 Update: Debug the Event objects with Stackdriver Logging for Google Apps Script. From the menu bar in the script editor, goto: View > Stackdriver Logging to view or stream the logs.

2017更新:为谷歌应用程序脚本进行Stackdriver日志记录调试。在脚本编辑器的菜单栏中,goto:查看> Stackdriver日志以查看或流日志。

console.log() will write DEBUG level messages

log()将编写调试级别的消息。

Example onEdit():

例子onEdit():

function onEdit (e) {
  var debug_e = {
    authMode:  e.authMode,  
    range:  e.range.getA1Notation(),    
    source:  e.source.getId(),
    user:  e.user,   
    value:  e.value,
    oldValue: e. oldValue
  }

  console.log({message: 'onEdit() Event Object', eventObject: debug_e});
}

Example onFormSubmit():

例子onFormSubmit():

function onFormSubmit (e) {
  var debug_e = {
    authMode:  e.authMode,  
    namedValues: e.namedValues,
    range:  e.range.getA1Notation(),
    value:  e.value
  }

  console.log({message: 'onFormSubmit() Event Object', eventObject: debug_e});
}

Example onChange():

例子onChange():

function onChange (e) {
  var debug_e = {
    authMode:  e.authMode,  
    changeType: changeType,
    user:  e.user
  }

  console.log({message: 'onChange() Event Object', eventObject: debug_e});
}

Then check the logs in the Stackdriver UI labeled as the message string to see the output

然后,检查Stackdriver UI中标记为消息字符串的日志,以查看输出。

#1


66  

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()触发函数的示例。它通过一个事件对象,在理解事件中使用“电子表格编辑事件”所描述的所有信息。

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

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

/**
 * Test function for onEdit. Passes an event object to simulate an edit to
 * a cell in a spreadsheet.
 *
 * Check for updates: https://*.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"
  });
}

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

如果你好奇,这是为了测试谷歌电子表格的onEdit函数,条件是三个单元格。

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?.

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

/**
 * Test function for Spreadsheet Form Submit trigger functions.
 * Loops through content of sheet, creating simulated Form Submit Events.
 *
 * Check for updates: https://*.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://*.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:

    电子表格提交事件:

    • all namedValues values are arrays.
    • 所有的namedValues值都是数组。
    • 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.
    • 正如第4335期所述,值数组跳过空白答案(在“新表单”+“新表单”中)。使用filter(Boolean)方法来模拟这种行为。

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

*一个格式为“纯文本”的单元格将把日期保存为字符串,这不是一个好主意。

#2


2  

2017 Update: Debug the Event objects with Stackdriver Logging for Google Apps Script. From the menu bar in the script editor, goto: View > Stackdriver Logging to view or stream the logs.

2017更新:为谷歌应用程序脚本进行Stackdriver日志记录调试。在脚本编辑器的菜单栏中,goto:查看> Stackdriver日志以查看或流日志。

console.log() will write DEBUG level messages

log()将编写调试级别的消息。

Example onEdit():

例子onEdit():

function onEdit (e) {
  var debug_e = {
    authMode:  e.authMode,  
    range:  e.range.getA1Notation(),    
    source:  e.source.getId(),
    user:  e.user,   
    value:  e.value,
    oldValue: e. oldValue
  }

  console.log({message: 'onEdit() Event Object', eventObject: debug_e});
}

Example onFormSubmit():

例子onFormSubmit():

function onFormSubmit (e) {
  var debug_e = {
    authMode:  e.authMode,  
    namedValues: e.namedValues,
    range:  e.range.getA1Notation(),
    value:  e.value
  }

  console.log({message: 'onFormSubmit() Event Object', eventObject: debug_e});
}

Example onChange():

例子onChange():

function onChange (e) {
  var debug_e = {
    authMode:  e.authMode,  
    changeType: changeType,
    user:  e.user
  }

  console.log({message: 'onChange() Event Object', eventObject: debug_e});
}

Then check the logs in the Stackdriver UI labeled as the message string to see the output

然后,检查Stackdriver UI中标记为消息字符串的日志,以查看输出。