0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【MCP不要】Figma REST APIからVitestのテストコードを自動生成

0
Last updated at Posted at 2026-11-30

この記事はアイスタイル Advent Calendar 2026 1日目の記事です。

📚 はじめに

フロントエンド開発において実装中の要件変更やリリース後の運用や改修を重ねるうちにFigma上のデザインと実装コードが徐々に乖離していくのはよくある課題です。

  • 細かい文言修正がFigma上で行われたが、実装への反映が漏れていた
  • テキスト内リンクのhrefが仮置きの#のまま残っていた
  • 見た目はボタンなのに<div>で実装され、デザインの意図とコードの意味が異なっていた

こうした乖離を防ぐには常にデザインを正として扱い、デザインの変更がそのままコードへ反映される運用にするのが理想です。
最近はFigma MCPを利用しデザインからコードを書きだす方法もありますが、セキュリティや組織の要件から利用が難しい場面も少なくありません。
今回はMCPを使わずFigma REST APIから取得したデザイン構造のJSONを変換し、Nuxt3+Vitestのテストコードを自動生成するスクリプトを作成したのでご紹介します。
※ スクリプトはAIに書いてもらいました。※

🔧 全体の仕組み

  1. Figma REST APIから対象画面(Frame)のノード情報をJSONとして取得
  2. 変換スクリプトでJSONから、見出し・テキスト・リンク・ボタンを抽出
  3. Vitest用のテストファイルを自動出力
  4. npx vitest runで実際のVueコンポーネントをマウントし、構造と文言をチェック

📸 今回テストコードを出力するデザイン

image.png

テキストとリンクとボタンのシンプルな構成です。
テキストレイヤーにリンクを持たせることで、このままaタグに変換できるようにしています。

レイヤー構成

image.png

📛 Figma側の命名ルール

JSONから「何の要素か」を機械的に判定するため、Figmaのレイヤー名に簡単なプレフィックスを付けました。

  • h1: で始まるテキスト → <h1>タグの完全一致チェック
  • btn: で始まるグループ → <button>または<a>の存在&ラベル一致チェック
  • 通常のテキストノード → 改行(<br> 想定)ごとに分割して画面内テキストの存在チェック
  • テキスト内のハイパーリンク設定 → <a>タグの存在・hrefの設定漏れ(#禁止)・パス一致チェック(URL末尾に #external を付けると外部リンク用クラスも検証)

🌎 環境

今回はNuxt3プロジェクトを用意し、 @nuxt/test-utilsとhappy-domを導入しました。

🤖 実装:Figma JSON → Vitest変換スクリプト

scripts/generate-figma-tests.cjs

const fs = require('fs');
const path = require('path');

// テスト生成のマッピング設定
const TARGET_MAPPINGS = [
  {
    figmaFrameName: 'ご利用上の注意',
    componentName: 'TermsNotice',
    importPath: '~/components/TermsNotice.vue',
    outputPath: 'tests/generated/TermsNotice.figma.spec.ts',
  },
];

// テキスト内のリンクプロパティ(characterStyleOverrides)を抽出
function extractHyperlinks(node) {
  const { characters, characterStyleOverrides, styleOverrideTable } = node;
  if (!characters || !characterStyleOverrides || !styleOverrideTable) return [];

  const rawLinks = [];
  let currentText = '';
  let currentUrl = null;

  for (let i = 0; i < characters.length; i++) {
    const styleId = characterStyleOverrides[i] || 0;
    const hyperlink = styleId !== 0 && styleOverrideTable[styleId] ? styleOverrideTable[styleId].hyperlink : null;
    const url = hyperlink && hyperlink.type === 'URL' ? hyperlink.url : null;

    if (url) {
      if (currentUrl === url) {
        currentText += characters[i];
      } else {
        if (currentText && currentUrl) rawLinks.push({ text: currentText.trim(), url: currentUrl });
        currentText = characters[i];
        currentUrl = url;
      }
    } else if (currentText && currentUrl) {
      rawLinks.push({ text: currentText.trim(), url: currentUrl });
      currentText = '';
      currentUrl = null;
    }
  }
  if (currentText && currentUrl) {
    rawLinks.push({ text: currentText.trim(), url: currentUrl });
  }

  return rawLinks
    .filter((item) => item.text.length > 0)
    .map((item) => {
      try {
        const parsed = new URL(item.url);
        const cleanPath = parsed.pathname.replace(/\/+/g, '/');
        return {
          text: item.text,
          pathname: cleanPath && cleanPath !== '/' ? cleanPath : null,
          isExternal: parsed.hash === '#external',
        };
      } catch {
        return { text: item.text, pathname: null, isExternal: false };
      }
    });
}

// 配下の最初のTEXTを取得(btn: 配下用)
function findFirstText(node) {
  if (node.type === 'TEXT' && node.characters) {
    return node.characters.trim();
  }
  if (Array.isArray(node.children)) {
    for (const child of node.children) {
      const found = findFirstText(child);
      if (found) return found;
    }
  }
  return '';
}

// ノードを再帰的に走査してアサーション文字列を組み立てる
function parseNodeToAssertions(node, state = { linkCount: 0, btnCount: 0 }) {
  if (!node || node.visible === false) return '';

  const type = node.type;
  const name = node.name || '';
  let code = '';

  // 1. 見出し (h1:〜)
  if (name.startsWith('h1:') && node.characters) {
    const heading = node.characters.replace(/\s+/g, ' ').trim();
    code += `    expect(wrapper.find('h1').text()).toBe(${JSON.stringify(heading)});\n\n`;
    return code;
  }

  // 2. ボタン (btn:〜)
  if (name.startsWith('btn:')) {
    const label = findFirstText(node).replace(/\s+/g, ' ');
    if (label) {
      const varName = `btn${state.btnCount++}`;
      code += `    const ${varName} = wrapper.findAll('button, a').find((el) => el.text().includes(${JSON.stringify(label)}));\n`;
      code += `    expect(${varName}?.exists()).toBe(true);\n\n`;
    }
    return code;
  }

  // 3. テキストノード
  if (type === 'TEXT' && node.characters && !name.startsWith('$')) {
    const lines = node.characters.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
    for (const line of lines) {
      code += `    expect(wrapper.text()).toContain(${JSON.stringify(line)});\n`;
    }
    if (lines.length > 0) code += '\n';

    const links = extractHyperlinks(node);
    for (const link of links) {
      const varName = `link${state.linkCount++}`;
      const hrefVar = `${varName}Href`;
      code += `    const ${varName} = wrapper.findAll('a').find((a) => a.text().includes(${JSON.stringify(link.text)}));\n`;
      code += `    expect(${varName}?.exists()).toBe(true);\n`;
      code += `    const ${hrefVar} = ${varName}?.attributes('href');\n`;
      code += `    expect(${hrefVar}).toBeTruthy();\n`;
      code += `    expect(${hrefVar}).not.toBe('#');\n`;
      if (link.pathname) {
        code += `    expect(${hrefVar}).toContain(${JSON.stringify(link.pathname)});\n`;
      }
      if (link.isExternal) {
        code += `    expect(${varName}?.classes()).toContain('external');\n`;
      }
      code += '\n';
    }
    return code;
  }

  // 4. コンテナの子要素を再帰処理
  if (Array.isArray(node.children)) {
    for (const child of node.children) {
      code += parseNodeToAssertions(child, state);
    }
  }

  return code;
}

// JSON内から対象Frameを検索(/files と /files/nodes 両対応)
function findTargetFrame(json, targetName) {
  const roots = [];
  if (json.document) {
    roots.push(json.document);
  } else if (json.nodes) {
    for (const key of Object.keys(json.nodes)) {
      if (json.nodes[key] && json.nodes[key].document) {
        roots.push(json.nodes[key].document);
      }
    }
  } else {
    roots.push(json);
  }

  function search(node) {
    if (!node) return null;
    if (node.name === targetName || node.id === targetName) return node;
    if (Array.isArray(node.children)) {
      for (const child of node.children) {
        const found = search(child);
        if (found) return found;
      }
    }
    return null;
  }

  for (const root of roots) {
    const found = search(root);
    if (found) return found;
  }
  return null;
}

function main() {
  const argFileName = process.argv[2];
  if (!argFileName) {
    console.error('使用法: node scripts/generate-figma-tests.cjs <jsonファイル名>');
    process.exit(1);
  }

  const baseName = path.basename(argFileName);
  const fileName = baseName.endsWith('.json') ? baseName : `${baseName}.json`;
  const inputPath = path.resolve(__dirname, fileName);

  const rawData = fs.readFileSync(inputPath, 'utf8');
  if (!rawData.trim()) {
    console.error(`エラー: ${fileName} の中身が空です。`);
    process.exit(1);
  }

  const figmaJson = JSON.parse(rawData);
  const projectRoot = path.resolve(__dirname, '..');

  for (const mapping of TARGET_MAPPINGS) {
    const targetFrame = findTargetFrame(figmaJson, mapping.figmaFrameName);
    if (!targetFrame) continue;

    const assertionsCode = parseNodeToAssertions(targetFrame);
    const testFileOutput = `// Auto-generated from ${fileName}. Do not edit manually.
import { describe, it, expect } from 'vitest';
import { mountSuspended } from '@nuxt/test-utils/runtime';
import ${mapping.componentName} from '${mapping.importPath}';

describe('${mapping.componentName} (Figma Structure Check)', () => {
  it('Figmaで定義された要素・文言が存在すること', async () => {
    const wrapper = await mountSuspended(${mapping.componentName});

${assertionsCode.trimEnd()}
  });
});
`;

    const outPath = path.resolve(projectRoot, mapping.outputPath);
    fs.mkdirSync(path.dirname(outPath), { recursive: true });
    fs.writeFileSync(outPath, testFileOutput, 'utf8');
    console.log(`${mapping.outputPath} を生成しました。`);
  }
}

main();

🏃 実行手順と自動生成されたテストコード

1. Figma REST API から JSON を取得

今回は個人アクセストークンを利用して取得します。
トークンは設定>セキュリティ>個人アクセストークンから取得可能です。

curlコマンドでトークンをヘッダーに渡してJSONを取得しに行きます。

curl -k -S -H  "X-Figma-Token: <FIGMA_TOKEN>" \
"https://api.figma.com/v1/files/<FILE_KEY>/nodes?ids=<NODE_ID>" \
-o figma.json

下記を参考にしました。

2. テストファイルの生成

node generate-figma-tests.cjs figma.json

実際に自動生成されたtests/generated/TermsNotice.figma.spec.tsは以下のようになります。

// Auto-generated from figma-qiita.json. Do not edit manually.
import { describe, it, expect } from 'vitest';
import { mountSuspended } from '@nuxt/test-utils/runtime';
import TermsNotice from '~/components/TermsNotice.vue';

describe('TermsNotice (Figma Structure Check)', () => {
  it('Figmaで定義された要素・文言が存在すること', async () => {
    const wrapper = await mountSuspended(TermsNotice);

    const btn0 = wrapper.findAll('button, a').find((el) => el.text().includes("同意してサービスを利用"));
    expect(btn0?.exists()).toBe(true);

    expect(wrapper.text()).toContain("本サービスをご利用いただくにあたり、");
    expect(wrapper.text()).toContain("注意事項への同意が必要です。");
    expect(wrapper.text()).toContain("注意事項はこちらよりご確認ください。");

    const link0 = wrapper.findAll('a').find((a) => a.text().includes("注意事項はこちら"));
    expect(link0?.exists()).toBe(true);
    const link0Href = link0?.attributes('href');
    expect(link0Href).toBeTruthy();
    expect(link0Href).not.toBe('#');
    expect(link0Href).toContain("/terms");

    expect(wrapper.find('h1').text()).toBe("サービスのご利用上の注意");
  });
});

🎯 結果と付け足し解説

npx vitest run

成功したとき

 ✓ tests/generated/TermsNotice.figma.spec.ts (1 test) 160ms
   ✓ TermsNotice (Figma Structure Check) (1)
     ✓ Figmaで定義された要素・文言が存在すること 38ms

 Test Files  1 passed (1)
      Tests  1 passed (1)

失敗したとき

AssertionError: expected '#' not to be '#' // Object.is equality
 ❯ tests/generated/TermsNotice.figma.spec.ts:21:27
     19|     const link0Href = link0?.attributes('href');
     20|     expect(link0Href).toBeTruthy();
     21|     expect(link0Href).not.toBe('#');
       |                           ^
     22|     expect(link0Href).toContain("/terms");
     23|

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯


 Test Files  1 failed (1)
      Tests  1 failed (1)

⇒ 「テキスト内リンクのhrefが仮置きの#のまま残っていた」という失敗させたところ、想定通りの拾い方をしてくれました。
リンクについては、本番環境/検証環境/開発環境でドメインが変わることを想定し、パスのみを検証するようにテストを書き起こしています。

🤔 実装中にハマったポイント

  1. Figmaトークンのスコープ違い
    本来はfile_content:read(ファイルのコンテンツ読み取り)のスコープが必要でしたが、誤って file_comments:read(コメント読み取り)を設定してしまい、すこし詰まりました。
  2. URLのnode-idの形式違い
    ブラウザのURLは?node-id=1-2とハイフン区切りですが、REST API のidsパラメータは1:2とコロン区切りにする必要がありました。

🎅 おわりに

FigmaのJSON構造をそのままVitestのファイルに変換することで、デザインの文言・リンク・タグ構造を仕様書兼自動テストとして扱えるようになりました。
今後は要素の多い画面でのコード化の検証も進めていく予定です。

ご覧いただきありがとうございました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?