从 ClientFunction 中访问全局变量
Access a global variable from within a ClientFunction
我想知道是否可以从 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 中访问变量?
客户端函数有 certain limitations and cannot access variables defined in the outer scope. I also suggest you consider passing the necessary variables through the Client Function's options.dependencies
个对象:
import { Selector, ClientFunction } from 'testcafe';
const articleHeader = Selector('#article-header');
const getArticleHeaderHTML = ClientFunction(() => articleHeader().innerHTML, {
dependencies: { articleHeader }
});
我想知道是否可以从 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 中访问变量?
客户端函数有 certain limitations and cannot access variables defined in the outer scope. I also suggest you consider passing the necessary variables through the Client Function's options.dependencies
个对象:
import { Selector, ClientFunction } from 'testcafe';
const articleHeader = Selector('#article-header');
const getArticleHeaderHTML = ClientFunction(() => articleHeader().innerHTML, {
dependencies: { articleHeader }
});