使用节点执行独立 javascript 文件时,我可以使用got成功执行 API 调用
但是我在执行来自量角器规范文件的相同请求时面临挑战。
文件夹结构
.
├── 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
}
问题
现在,我正在尝试在 Protractor 脚本中执行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), null, 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 请求时在 Protractor 中引发异常
$ ./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;
感谢您阅读所有内容。非常感谢解决ECONNREFUSED错误的任何帮助。