1
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?

【TanStack Router × Vitest】`npm run test`を実行時に発生した`Client-only API called on the server side`の解決方法

1
Posted at

はじめに

Tanstack RouterとVitestを利用してテスト実行時に発生したエラー解決方法についてまとめたものになります。

エラーと発生時の環境

以下の記事で紹介されているTanstack RouterとVitestを利用したIntegrationテストを作成し、実行した際に起こりました。

発生した際に表示されたエラー文はこちらです。

エラー文
Error: Client-only API called on the server side. Run client-only code in onMount, or conditionally run client-only component with <Show>.
    at render 
    at TanStackDevtoolsCore.mount

▼ 参考にした記事

原因

エラー文内を見てもらうとわかるように、エラーの発生箇所がTanStackDevtoolsCoreとなっています。
原因は、TanStack RouterのデバッグツールであるTanStack Devtoolsコンポーネントを、テスト環境でレンダリングしたことによって起きています。
TanStack DevtoolsはクライアントサイドAPIを使用するため、テスト環境(jsdom)では「サーバーサイド」として扱われ、エラーとなった次第です。

対応策

テスト時に、TanStack Devtoolsコンポーネントがレンダリングされなければ良いので、環境に応じた条件付きレンダリングを利用して解決しました。
大体の人がTanStack Devtoolsコンポーネントを__root.tsx内に置いていると思うので以下の用に修正してください。

_root.tsx
import { TanstackDevtools } from "@tanstack/react-devtools";
import type { QueryClient } from "@tanstack/react-query";
import { ReactQueryDevtoolsPanel } from "@tanstack/react-query-devtools";
import { createRootRouteWithContext, Outlet } from "@tanstack/react-router";
import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools";

export const Route = createRootRouteWithContext<{
  queryClient: QueryClient;
}>()({
  component: () => (
    <>
      <Outlet />
      {/* テスト環境では開発ツールを無効化 */}
      {!import.meta.env.TEST && (
        <TanstackDevtools
          config={{
            position: "bottom-left",
          }}
          plugins={[
            {
              name: "Tanstack Router",
              render: <TanStackRouterDevtoolsPanel />,
            },
            {
              name: "Tanstack Query",
              render: <ReactQueryDevtoolsPanel />,
            },
          ]}
        />
      )}
    </>
  ),
});

次に、条件付きレンダリングに使用している環境変数の設定を行います。

vite.config.ts
import { tanstackRouter } from "@tanstack/router-plugin/vite";
import viteReact from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";
import { defineConfig } from "vitest/config";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    tanstackRouter({ autoCodeSplitting: true }),
    viteReact(),
    tsconfigPaths(),
  ],
  test: {
    globals: true,
    environment: "jsdom",
    setupFiles: ["./tests/setup.ts"],
    include: ["tests/**/*.test.{ts,tsx}"],
    exclude: ["**/node_modules/**"],
  },
  define: {
    // このようにして、定義を行う
    "import.meta.env.TEST": JSON.stringify(process.env.NODE_ENV === "test"),
  },
});

おわりに

テスト環境によってレンダリングされるもの、されないものを意識していなかったため、次から気をつけていきたいです

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼

1
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
1
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?