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?

More than 1 year has passed since last update.

registerEndpointでは有効な値を返すようにしよう

Posted at

以下のようなAPIがあり、これを含むコンポーネントをテストしたいとする。

<template>
  ...
</template>

<script setup lang="ts">
const add = async () => {
  await $fetch("/api/add", {
    method: "POST"
  })
  console.log('追加しました')
}
</script>

テストコードでregisterEndpointを使い、APIレスポンスをモックする。
ここで、戻り値を使わないのでhandlerに空の関数を定義するとエラーとなる。

it('test', async () => {
  registerEndpoint("/api/add", {
    method: "POST",
    handler: () => {}
  })

  const component = await mountSuspended(HogeComponent)
  await component.setupState["add"]();
})
テスト結果
FAIL  components/HogeComponent.spec.ts > HogeComponent > test
FetchError: [POST] "/api/add": 404 Cannot find any path matching /.
 ❯ $fetch2 node_modules/ofetch/dist/shared/ofetch.37386b05.mjs:268:15
 ❯ components/HogeComponent.spec.ts:22:5
     20|       handler: () => {},
     21|     });
     22|     await $fetch("/api/add", {
       |     ^
     23|       method: "POST",
     24|     });

エラー文が分かりづらいですが、handlerに有効な値を返す関数を追加したところテスト成功しました。

it('test', async () => {
  registerEndpoint("/api/add", {
    method: "POST",
-   handler: () => {}
+   handler: () => ""
  })

  const component = await mountSuspended(HogeComponent)
  await component.setupState["add"]();
})

本来/api/addはvoidを返すAPIなので気持ち悪いですが...
もし他に良い書き方があれば教えて頂けますと幸いです :bow:


以下参考

エラーになるhandler
() => {}

() => undefined

() => {
  return
}

() => {
  return undefined
}
成功するhandler
() => null

() => ""

() => 0

() => false

() => {
  return {}
}
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?