intermock 사용 방법이 아직 잘 나와있지 않아서 소스코드 보면서 츄라이츄라이 해본 결과입니다. 엉성하더라도 참고할 것이 아예 없는 것보다는 낫...낫지 않을까..? 싶어서 정리해보았습니다. ㅎㅎ intermock 사용 방법을 찾고 계신 분께 부디 제 코드가 조금이라도 도움이 되길 바라며..

설치 필요 모듈

  • intermock : TS interface를 이용하여 mock data를 생성할 수 있게 도와주는 모듈
  • swagger-typescript : intermock을 위한 TS interface를 생성하고 이를 단일 파일에 모아두기 위해 사용
    • 인터페이스를 생성해주는 라이브러리라면 어떤 것이든 무관하나, 인터페이스들을 단일 파일이 아니라 모델별로 생성해주는 경우에는 intermock 사용 전에 각각의 파일에서 인터페이스들을 가져와서 하나의 파일로 만들어주는 로직을 추가해야 함.
    • 왜냐하면 intermock은 파일 외부로부터 불러오는 타입을 무시해버림. 😓
    • swagger-typescript처럼 인터페이스 생성해주는 라이브러리로는 openapi-generator, swagger-typescript-api 등이 있음.
  • minimist : 커맨드 라인에서 입력된 인자값들을 편리하게 가져오기 위해 사용

 

방법

1. 위 설치 필요 모듈의 3가지 모듈 모두 설치

2. swagger-typescript를 이용하여 스웨거 API 문서로부터 인터페이스 추출

  • 루트 디렉토리에 swagger.config.json 파일 추가
{
  "url": "http://{스웨거명세서}/openapi.json",
  "dir": "./mock",
  "prefix": "/api",
  "language": "typescript"
}
  • (패키지 매니저로 yarn 쓰면) yarn swag-ts 명령어를 입력하여 swagger-typescript 실행
  • mock/types.ts 파일이 생성되고 인터페이스가 정상적으로 추출된 것 확인

3. intermock을 이용하여 2.에서 추출한 인터페이스를 기반으로 mock data 생성

  • 스크립트 파일 작성(scripts/mock.js)
// scripts/mock.js
const { mock } = require('intermock');
const fs = require('fs');
const parseArgs = require('minimist');

/**
 * 특정 인터페이스에 대한 mock data를 생성합니다.
 * @function
 * @param {string} filePath - required> 대상 인터페이스가 선언된 파일의 상대경로 (예: ./mock/types.ts)
 * @param {string} typeName - required> 대상 인터페이스 이름 (예: NoticeWithId)
 * @param {string} output - optional> 생성할 mock data 파일명 (예: coupon) - 지정하지 않을 경우 ./mock/data.js
 * @param {number} length - optional> 생성할 mock data 아이템 개수 - 지정하지 않을 경우 1개만 생성
 */
function generateMock({
  filePath = '',
  typeName = '',
  output = 'data',
  length = 1,
}) {
  if (!filePath || !typeName) {
    console.info('\x1b[35m', `📌 'yarn run mock <파일명> <타입명> [--output=<파일명>] [--length=<개수>]'`, '\x1b[37m', '으로 입력해주세요.');
    return;
  }

  const fileContent = fs.readFileSync(filePath);
  let count = length;

  if (length <= 1) {
    count = 1;
  }

  const emptyArray = new Array(count).fill(0);
  const mocks = emptyArray.map(() => {
    const mocked = mock({
      files: [ [ filePath, String(fileContent) ] ],
      interfaces: [ typeName ],
      language: 'typescript',
    });

    return mocked[typeName];
  });

  const outputString = `const ${output} = ${JSON.stringify(mocks)}; \nexport default ${output};`;

  fs.writeFileSync(`./mock/data/${output}.js`, outputString, 'utf8');
  console.log('\x1b[36m', `🎉 mock data가 준비되었습니다! \n ./mock/data/${output}.js 으로 바로가기`);
}

const args = process.argv.slice(2);
const [ filePath, typeName ] = args;
const { output, length } = parseArgs(args);

generateMock({
  filePath,
  typeName,
  output,
  length,
});
  • package.json에 스크립트 추가
scripts: {
    ...
    "mock": "node scripts/mock.js"
}
  • 터미널에서 커맨드 입력
yarn run mock ./mock/types.ts NoticeWithId --output=notice --length=3
  • mock/data/notice.js 파일이 생성되고 mock data가 타입에 맞게 생성된 것 확인

 

복사했습니다!