Nodejs 로 Http GET 메시지 테스트 하기
Nodejs 를 사용해서 Http GET 테스트를 진행 해보기로 했습니다.
이유는 있을리가 없습니다...ㅋ
1. Nodejs 다운받기
https://nodejs.org/en/download/
Download | Node.js
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org
저는 밑줄 친 그것을 받겠습니다.
예전에는 인스톨러 버전만 있었던 것 같은 데 지금은 바이너리 버전도 있네요~
https://blog.naver.com/tommybee/221096155945
nodejs 설치 및 grunt 설정
일단 두서 없이 써두는 것으로... nodjs를 설치 하는 것부터 시작한다. 신뢰도 높은 것으로 선택한다. ui-g...
blog.naver.com
그런 다음, 아무데나 풀어 놓습니다. 그리고 배치 파일 하나를 만들고
이렇게 해 주었습니다.
SET PATH=D:\DEV\SDK\node-v16.17.0-win-x64;%PATH%;
call cmd /K nodevars.bat
2. Http 테스트하기 -GET
그리고 능력이 안되는 관계로 소스를 하나 얻어 봅니다.
https://www.educative.io/answers/what-is-the-httpsget-method-in-node
What is the https.get() method in Node?
Contributor: Ayush Trivedi
www.educative.io
위 사이트에서 테스트를 해봐도 되는 데... 뭐 그럼 좀 그렇죠?
- jest 설치
jest 라는 테스트 툴이 있는 것 같은 데요. 이 라이브러리를 설치 해 줍니다.
npm install jest
npm install axios
- 테스트 모듈 만들기
테스트 모듈도 다음 사이트를 참고 해서 이리저리 만들어 봅니다.
순서는
- package.json 만들고,
- 실제 테스트 코드 만들고 - http_get.js -
- jest 용 테스트 코드를 만들어 -
주면 될 것 같습니다.
package.json
{"scripts":{"test":"jest"},"dependencies":{"jest":"^29.0.2"}}
http_get.js
module.exports = {
testHttpGet: (value) => {
const https = require('https');
https.get('https://www.naver.com',
(resp)=>{
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(data);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
return false;
},
};
nodejs_test1.spec.js
참고로 js 파일 바로 앞에 붙어 있는 spec 은 스팩이라고 합니다
const { testHttpGet } = require('./httpget_test');
test('테스트가 성공하는 상황', () => {
expect(testHttpGet('GET 메시지 성공')).toEqual(false);
});
실행하기
실행 해 볼까요?
D:\DEV\workspaces_js\mytest>npm test
> test
> jest
PASS ./nodejs_test1.spec.js
√ 테스트가 성공하는 상황 (51 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.514 s
Ran all test suites.
● Cannot log after tests are done. Did you forget to wait for something async in your test?
Attempted to log "Error: self signed certificate in certificate chain".
14 | // The whole response has been received. Print out the result.
15 | resp.on('end', () => {
> 16 | console.log(data);
| ^
17 | });
18 |
19 | }).on("error", (err) => {
at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
at ClientRequest.<anonymous> (httpget_test.js:16:15)
경사가 났네요~ 오류가 났어요~ 그래서 스택오버플로 선생님이 말씀 하시길...
nodejs - error self signed certificate in certificate chain
I am facing a problem with client side https requests. A snippet can look like this: var fs = require('fs'); var https = require('https'); var options = { hostname: 'someHostName.com', p...
stackoverflow.com
그래서 코드를 좀 바꿨습니다.
package.json
{"scripts":{"test":"jest"},"dependencies":{"axios":"^0.27.2","jest":"^29.0.2","js-file-download":"^0.4.12"}}
httpget_test.js
testHttpGet: (value) => {
const axios = require("axios");
const https = require("https");
var fileDownload = require('js-file-download');
const url = 'https://www.naver.com';
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const options = {
method: "get",
responseType: 'arraybuffer',
//headers: {
// "User-Agent": "test",
//},
httpsAgent: new https.Agent({
rejectUnauthorized: false,
}),
};
axios(url, options)
.then((res) => {
console.log(res.data);
//console.log(JSON.stringify(res.data));
//fileDownload(res.data, 'filename.csv');
//console.log(res.data);
//const writableStream = fs.createWriteStream('aaa.ts');
//writableStream.write(res.data);
//writableStream.end();
//writableStream.on('finish', () => {
// console.log(`All your sentences have been written to ${filePath}`);
//})
//setTimeout(() => {
// process.exit(0);
//}, 100);
return true;
})
.catch((error) => console.log(error));
return false;
},
nodejs_test1.spec.js
참고로 js 파일 바로 앞에 붙어 있는 spec 은 스팩이라고 합니다
const { testHttpGet } = require('./httpget_test');
test('테스트가 성공하는 상황', async () => {
//expect.assertions(1);
const result = await testHttpGet('GET 메시지 성공'); // let the Promise resolve
//const data = result.getStatus(); // call getStatus on the result
expect(result).toEqual(false);
//done();
});
참고 사이트
https://www.educative.io/answers/what-is-the-httpsget-method-in-node
What is the https.get() method in Node?
Contributor: Ayush Trivedi
www.educative.io
https://goddaehee.tistory.com/268
[Java] HttpsURLConnection
[Java] HttpsURLConnection 안녕하세요. 갓대희 입니다. 이번 포스팅은 [ [Java] HttpsURLConnection ] 입니다. : ) 0.HttpsURLConnection ▶ 0. HttpsURLConnection란? - JAVA 소스 내에서 SSL 적용..
goddaehee.tistory.com
http://www.javased.com/index.php?api=javax.net.ssl.TrustManager
Java Code Examples of javax.net.ssl.TrustManager
Java Code Examples for javax.net.ssl.TrustManager The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you. Example 1 From project 4308Cirrus, under directory /tendril-android-lib/src
www.javased.com
Easy way to write contents of a Java InputStream to an OutputStream
I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviously, the byte buffer code isn't difficult to write,...
stackoverflow.com
https://seungjuitmemo.tistory.com/269
Nodejs: 테스트 코드 작성하기(feat. Jest)
이번 포스팅은 테스트 코드의 원칙과 Jest를 이용한 단위 테스트 코드 작성에 대해 포스팅한다. 1. 테스트 코드란 무엇일까? 테스트 코드는 말 그대로 우리가 작성한 코드에 문제가 없는지 테스트
seungjuitmemo.tistory.com
https://yeonfamily.tistory.com/18
Node.js | self signed certificate (자체 서명 인증서) 에러 발생 원인과 Axios에서 해결 해보기
개요 SSL 요청 중 발생할 수 있는 self signed certificate 에러의 발생 원인과 Node.js의 Axios를 통한 해결방법을 공유해보려 합니다. self signed certificate(자체 서명 인증서) 에러 발생 원인에 대해서는 py..
yeonfamily.tistory.com
nodejs - error self signed certificate in certificate chain
I am facing a problem with client side https requests. A snippet can look like this: var fs = require('fs'); var https = require('https'); var options = { hostname: 'someHostName.com', p...
stackoverflow.com
https://yamoo9.github.io/axios/guide/error-handling.html
오류 처리 | Axios 러닝 가이드
오류 처리 axios 라이브러리 오류 처리 방법은 다음과 같습니다. axios.get('/user/12345') .catch(function (error) { if (error.response) { console.log(error.response.data); console.log(error.response.status); console.log(error.response.he
yamoo9.github.io
Jest did not exit one second after the test run has completed using express
I'm using JEST for unit testing my express routes. While running the yarn test all my test case are getting passed, but I'm getting an error Jest did not exit one second after the test run has
stackoverflow.com
Test an Async function in JS - Error: "Did you forget to use await"
My code looks like this: public getUrl(url) { //returns URL ... } public getResponseFromURL(): container { let myStatus = 4; const abc = http.get(url, (respon) => const { statusCode } =
stackoverflow.com
https://di-rk.medium.com/async-and-jest-lessons-learned-1aec0209f5d4
Async and Jest — Lessons Learned
or Did you forget to wait for something async in your test? That was the output of my console lately, in detail:
di-rk.medium.com
https://www.digitalocean.com/community/tutorials/how-to-work-with-files-using-streams-in-node-js
How To Work with Files Using Streams in Node.js | DigitalOcean
www.digitalocean.com
https://stackoverflow.com/questions/27159179/how-to-convert-blob-to-file-in-javascript
How to convert Blob to File in JavaScript
I need to upload an image to NodeJS server to some directory. I am using connect-busboy node module for that. I had the dataURL of the image that I converted to blob using the following code:
stackoverflow.com
https://stackoverflow.com/questions/49040247/download-binary-file-with-axios
Download binary file with Axios
For example, downloading of PDF file: axios.get('/file.pdf', { responseType: 'arraybuffer', headers: { 'Accept': 'application/pdf' } }).then(response => { const bl...
stackoverflow.com
https://www.npmjs.com/package/js-file-download
js-file-download
Javascript function that triggers browser to save javascript-generated content to a file. Latest version: 0.4.12, last published: 2 years ago. Start using js-file-download in your project by running `npm i js-file-download`. There are 252 other projects in
www.npmjs.com
https://stackoverflow.com/questions/49040247/download-binary-file-with-axios
Download binary file with Axios
For example, downloading of PDF file: axios.get('/file.pdf', { responseType: 'arraybuffer', headers: { 'Accept': 'application/pdf' } }).then(response => { const bl...
stackoverflow.com