问题描述
使用节点执行独立的javascript文件时,我可以成功使用got执行API调用
但是在执行来自量角器规格文件的相同got请求时,我面临挑战。
文件夹结构
.
├── build
│ ├── GotImpl.js
│ ├── basic-node-test.js
│ └── protractor-test.js
├── config
│ └── protractor.config.js
├── globals.js
├── package-lock.json
├── package.json
├── src
│ ├── GotImpl.ts
│ ├── basic-node-test.ts
│ └── protractor-test.ts
└── tsconfig.json
./ package.json
{
"name": "protractor-got","version": "1.0.0","description": "GOT and Protractor Test","main": "index.js","scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},"author": "","license": "ISC","dependencies": {
"@types/jasmine": "^3.5.14","@types/node": "^14.6.0","got": "^11.5.2","jasmine-data-provider": "^2.2.0","jasmine-expect": "^4.0.3","protractor": "^7.0.0"
},"devDependencies": {
"typescript": "^4.0.2"
}
}
./ tsconfig.js
{
"compilerOptions": {
"target": "es5","module": "commonjs","outDir": "build","strict": true,"esModuleInterop": true
}
}
./ src / GotImpl.ts -此类具有 executeGetRequest 方法,用于根据提供的requestURL执行get操作>
const got = require('got');
export class GotImpl {
options: any;
responseBody: any;
constructor() {
this.options = {};
this.options['headers'] = {};
this.options['method'] = "GET";
this.options.https = {};
this.options.https.rejectUnauthorized = false;
}
async executeGetRequest(requestURL: string): Promise<any> {
return new Promise<any>(async (resolve,reject) => {
let successfulExecution: boolean = false;
let apiRes = await got(requestURL,this.options);
resolve(await apiRes.body);
})
}
}
./ src / basic-node-test.ts -此文件是一个简单的TypeScript文件,可通过调用 GotImpl的 executeGetRequest 方法来执行get操作。 类
import { GotImpl } from "./GotImpl"
(async () => {
const gottest = new GotImpl();
await gottest.executeGetRequest('https://jsonplaceholder.typicode.com/todos/1').then(async (responseBody) => {
console.log('Response Body: ' + (await JSON.stringify(JSON.parse(responseBody),null,5)));
});
})();
执行basic-node-test.ts文件[成功执行]时的输出
$ node ./build/basic-node-test.js
Response Body: {
"userId": 1,"id": 1,"title": "delectus aut autem","completed": false
}
问题
现在,我正在尝试在量角器脚本中执行 executeGetRequest 方法(属于 GotImpl 类) >
./ src / protractor-test.ts -量角器规格文件
import { GotImpl } from "./GotImpl";
describe('Got in Protractor',() => {
it('Get Access Managers based on TIN',async (done) => {
console.log("Start of GOT Test");
const gottest = new GotImpl();
await gottest.executeGetRequest('https://jsonplaceholder.typicode.com/todos/1').then(async (responseBody) => {
console.log('Response Body: ' + (await JSON.stringify(JSON.parse(responseBody),5)));
});
console.log("End of GOT Test")
await done();
});
process.on('unhandledRejection',(reason) => {
console.error(reason);
process.exit(1);
});
});
./ globals.js -捕获全局变量
var path = require("path");
var fs = require("fs");
module.exports = function setGlobals() {
global.__root = path.dirname(fs.realpathSync(__filename));
global.__specs = path.join(__root,"/build/");
};
./ config / protractor.config.js
require('../globals').call();
var chromeHeadless = {
browserName: 'chrome',chromeOptions: {
args: [
"--no-sandBox","--headless","--disable-gpu","--window-size=800,600",'--disable-extensions','--disable-plugins','--disable-infobars'
],prefs: {
'profile.password_manager_enabled': false,'credentials_enable_service': false,'password_manager_enabled': false
}
}
}
exports.config = {
framework: 'jasmine',capabilities: chromeHeadless,directConnect: true,specs: [__specs + 'protractor-test.js']
}
使用got执行API请求时,在量角器中抛出了异常
$ ./node_modules/protractor/bin/protractor ./config/protractor.config.js
Start of Protractor Test Execution
[21:00:19] I/launcher - Running 1 instances of WebDriver
[21:00:19] I/direct - Using ChromeDriver directly...
Inside On Prepare method
End.....
Start of GOT Test
RequestError: connect ECONNREFUSED 127.0.0.1:443
at ClientRequest.<anonymous> (/Users/xxxx/MONO-REPO/protractor-project/node_modules/got/dist/source/core/index.js:891:25)
at Object.onceWrapper (events.js:422:26)
at ClientRequest.emit (events.js:327:22)
at ClientRequest.origin.emit (/Users/xxxx/MONO-REPO/protractor-project/node_modules/@szmarczak/http-timer/dist/source/index.js:39:20)
at TLSSocket.socketErrorListener (_http_client.js:426:9)
at TLSSocket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processticksAndRejections (internal/process/task_queues.js:84:21)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
code: 'ECONNREFUSED',timings: {
start: 1598493623188,socket: 1598493623189,lookup: 1598493623189,connect: undefined,secureConnect: undefined,upload: undefined,response: undefined,end: undefined,error: 1598493623190,abort: undefined,phases: {
wait: 1,dns: 0,tcp: undefined,tls: undefined,request: undefined,firstByte: undefined,download: undefined,total: 2
}
}
}
[21:00:23] E/launcher - Process exited with error code 1
目前采取的方法
- 已禁用NODE_TLS_REJECT_UNAUTHORIZED
- 在选项中设置隧道(在 GotImpl.ts 中)
const tunnel = require('tunnel');
this.tunnelingAgent = tunnel.httpOverHttps({
proxy: { // Proxy settings
host: process.env.PROXY_HOST,// Defaults to 'localhost'
port: process.env.PROXY_PORT,// Defaults to 80
proxyAuth: process.env.PROXY_AUTH,}
});
this.options.agent = {};
this.options.agent.https = this.tunnelingAgent;
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)