【问题标题】:Access a global variable from within a ClientFunction从 ClientFunction 中访问全局变量
【发布时间】:2019-10-10 09:16:27
【问题描述】:

我想知道是否可以从 ClientFunction 中访问变量,或者我是否应该始终将所需的参数传递给它?

我正在使用 TestCafe 的 ClientFunction 发出 HTTP 请求(创建新用户)。我们有多个环境,因此我不想将 URL 硬编码到请求中。

如果我将所需的 URL 传递给函数,则请求完成...但在尝试访问 createUserUrl 变量时收到错误消息。

import createUserUrl from '../config.js'.createUserUrl;

const createUserRequest = ClientFunction(userDetails => {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();

    xhr.open('POST', createUserUrl, true);

    xhr.onload = function() {
      resolve(xhr.responseText);
    };

    // Set headers:
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.send(JSON.stringify(userDetails));
  });
});

导致ReferenceError: reqUrl is not defined

否则,此选项有效

const createUserRequest = ClientFunction(reqUrl, userDetails => {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();

    xhr.open('POST', reqUrl, true);

    xhr.onload = function() {
      resolve(xhr.responseText);
    };

    // Set headers:
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.send(JSON.stringify(userDetails));
  });
});

第二个选项是首选路线,还是有办法从 ClientFunction 中访问变量?

【问题讨论】:

    标签: node.js automated-tests e2e-testing end-to-end testcafe


    【解决方案1】:

    客户端函数具有certain limitations 并且无法访问在外部范围中定义的变量。我还建议您考虑通过客户端函数的options.dependencies 对象传递必要的变量:

    import { Selector, ClientFunction } from 'testcafe';
    
    const articleHeader = Selector('#article-header');
    
    const getArticleHeaderHTML = ClientFunction(() => articleHeader().innerHTML, {
         dependencies: { articleHeader }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 2011-10-29
      • 2014-02-15
      相关资源
      最近更新 更多