frontend

프론트엔드 전체 테스트 환경 구축해보기(2.CLI)

하리하링웹 2024. 8. 30. 18:46

1편(설계) 보러가기

https://jjongsk.tistory.com/entry/1%ED%94%84%EB%A1%A0%ED%8A%B8%EC%97%94%EB%93%9C-%EC%A0%84%EC%B2%B4-%ED%85%8C%EC%8A%A4%ED%8A%B8-%ED%99%98%EA%B2%BD-%EA%B5%AC%EC%B6%95%ED%95%B4%EB%B3%B4%EA%B8%B0%EC%84%A4%EA%B3%84

 

프론트엔드 전체 테스트 환경 구축해보기(1.설계)

서론본격적으로 글을 작성하기에 앞서 요즘 하는 생각들을 주저리주저리 적어보자면, 고민이 이만저만이 아니다. 현재 회사가 마음에 들고 커리어적으로 엄청난 성장을 할 수 있을 것 

jjongsk.tistory.com

 

 

위 글에서 설계를 완료했으니 이제 다음 단계인 cli쪽을 개발해보자.

 

이 글을 쓰는 현재 웹 서버쪽을 개발중이고 개발 도중 몇 가지 수정해야 하는 부분이 있어 설계와 조금 변경된 부분들이 있지만 그 부분은 추후 웹 서버 개발 글을 작성할 때에 추가하도록 하겠다.

 

개발

Commander 설치

먼저 commander를 설치해준다. 이는 설계 단계에서 정의한 cli 실행을 위한 패키지이다.

> npm install --save-dev commander

 

Package.json 변경

cli 명령어 등록을 위해 먼저 package.json에 bin항목을 추가해준다. 이를 통해 cli 환경에서 ecdev runTest --path 와 같은 형태로 내가 원하는 코드를 실행 시킬 수 있다.

 

"name":"ecdev",
"version:"1.0.0",
"bin": {
        "ecdev": "./dist/ecdev/cli/test-runner.js"
 },
...

 

package.json의 bin 항목에는 파일의 경로만 넣어줄 수 있고 node와 같은 명령어를 넣는것은 불가능하다 따라서 타겟 파일 상단에 #!c:/progra~1/nodejs/node 와 같이 shebang을 추가하여 해당 파일이 node로 실행되는 파일임을 알려준다. 이를 통하여 앞에 node 없이 경로 입력만으로 실행이 가능해진다. 위 명령어는 window 환경에서 동작하는 명령어이며 unix 환경에서는 #!/usr/bin/env node 라는 다른 형태로 명시해줘야 한다.

 

아래는 예시 파일이다.

#!c:/progra~1/nodejs/node
import { Command } from 'commander';

const program = new Command();

program.name('ecdev').description('CLI tool for EC development').version('1.0.0');

// runTest 명령어를 ecdev의 하위 명령어로 정의
program
    .command('runTest <path>') // ecdev runTest [path] 형식으로 실행
    .description('Run the test at the specified path')
    
program.parse(process.argv);

 

npm link

이후 아래 명령어를 입력해준다.

> npm link

 

이를통해 현재 로컬의 패키지를 전역적으로 링크하여 사용할 수 있게된다. 추후 실제 배포시에는 npm install -g [package]를 통해 설치하도록 유도해야한다.

 

이제 명령어를 입력해보면 잘 동작하는 것을 확인할 수 있다.

PS D:\\builder> ecdev
Usage: ecdev [options] [command]

CLI tool for EC development

Options:
  -V, --version   output the version number
  -h, --help      display help for command

Commands:
  runTest <path>  Run the test at the specified path
  help [command]  display help for command

 

 

타겟파일 코드 작성

기본적은 환경은 구축했으니 이제 명령어 입력 시 해당 정보를 기반으로 서버를 실행시키는 코드가 작성되어있는 node 파일을 실행하도록 타겟 파일의 코드를 수정한다. 아래는 수정한 파일 내용이다.

#!c:/progra~1/nodejs/node
import { Command } from 'commander';
import { exec } from 'child_process';

const program = new Command();

program.name('ecdev').description('CLI tool for EC development').version('1.0.0');

// runTest 명령어를 ecdev의 하위 명령어로 정의
program
    .command('runTest <path>') // ecdev runTest [path] 형식으로 실행
    .description('Run the test at the specified path')
    .action((path) => {
        const child = exec(
            `node D:/[실행 경로]/index.js --targetFsPath=${path}`,
            (error, stdout, stderr) => {
                if (error) {
                    console.error(`Error: ${error.message}`);
                    return;
                }
                if (stderr) {
                    console.error(`Stderr: ${stderr}`);
                    return;
                }
                console.log(`Output: ${stdout}`);
            }
        );
        
        child.stdout?.on('data', (data) => {
            console.log(`[stdout]`, data.toString('utf8'));
        });

        child.stderr?.on('data', (data) => {
            console.error(`[stderr]`, data.toString('utf8'));
        });
    });

program.parse(process.argv);

 

파일을 위와 같이 변경하였다면 명령어 실행 시 정상적으로 작성해놓은 경로의 node 파일이 실행되며 서버가 실행되는 것을 확인할 수 있다. 물론 서버를 실행하는 node 파일이 존재해야하며 이는 웹 서버 작성 글에서 다루도록 하겠다.

PS D:\\builder> ecdev runTest D:builder
[stdout] {"level":30,"time":1724378941886,"pid":13932,"hostname":"test","msg":"Server listening at http://[::1]:30002"}

[stdout] {"level":30,"time":1724378941889,"pid":13932,"hostname":"test","msg":"Server listening at <http://127.0.0.1:30002>"}
undefined D:builder
[Listening] http://[::1]:30002
Press Ctrl + C to terminate

[stdout] {"level":30,"time":1724378942215,"pid":13932,"hostname":"test","reqId":"req-1","req":{"method":"GET","url":"/","hostname":"localhost:30002","remoteAddress":"::1","remotePort":54196},"msg":"incoming request"}

[stdout] {"level":30,"time":1724378942224,"pid":13932,"hostname":"test","reqId":"req-1","res":{"statusCode":200},"responseTime":8.89850000012666,"msg":"request completed"}

 

 

위 이미지에서 보이는 것 처럼 명령어 실행 시 추가적으로 적어놓은 경로도 같이 출력되는 것을 확인할 수 있다.

 

다음으로는 웹 서버 개발 혹은 vscode 단축키 등록 관련 글을 작성하도록 하겠다.