LoginSignup
2
2

More than 1 year has passed since last update.

React入門 - Part7 - mockサーバを利用してみる

Last updated at Posted at 2021-05-03

目次

mockサーバとは

外部APIにRESTアクセスし、結果を使用しフロント側のみ実装のテストをする場合などに使用します。
私が参加したプロジェクトだと、フロントのReactの実装が完了しAPIイベント部分の単体テストは、mockサーバで行っていました。
(実際のAPIへの接続は結合テスト段階で行っていました。)

mockサーバを試してみよう

ここを参考にしました。
「リクエストを投げてみる」までやればOKです。

手順はこれだけですね。
1. VSCodeにSwagger Editor拡張をインストール
2. prism-cli.exeをダウンロードしておく
3. sample.ymlをコピペで作成しておく
4. ./prism-cli.exe mock sample.ymlで起動
5. 画面で確認

1.2.は参考URLを見て準備してください。

3.のサンプルymlです。※UTF8で保存してください。

openapi: '3.0.2'
info:
  title: API Title
  version: '1.0'
servers:
  - url: https://api.server.test/v1
paths:
  /test:
    get:
      responses:
        '200':
          description: OK

5.表示画面はこのようになります。
データがないですね。

image.png

取得データを表示してみよう

sample.ymlを拡張して、以下のようにします。
(yamlの書き方は、ググれば沢山でてきますのでここでは割愛します。)

openapi: '3.0.2'
info:
  title: API Title
  version: '1.0'
servers:
  - url: https://api.server.test/v1
paths:
  /test:
    get:
      responses:
        '200':
          description: OK
          content:
            application/json: # レスポンスの形式指定
              schema: 
                type: array
                items:
                  $ref: '#/components/schemas/User' # 参照するモデル
                example: # サンプルデータ
                  - id: 1
                    name: John Doe
                  - id: 2
                    name: Jane Doe
components:
  schemas: # スキーマオブジェクトの定義
    User: # モデル名
      type: object # 型
      required: # 必須フィールド
        - id
      properties:
        id: # プロパティ名
          type: integer # 型 
          format: int64 # フォーマット(int32, int64等)
        name:
          type: string
    Product:
      type: object
      required:
        - id
        - price
      properties:
        id:
          type: integer
          format: int64
          example: 1
        name:
          type: string
          example: Laptop
        price:
          type: integer
          example: 1200                    

データが表示されました。

image.png

2
2
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
2
2