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

Vitestでカスタムフックをモック化したのにモックが効いていない

2
Posted at

はじめに

  • 久々にちゃんとテストコードを手書きしたけど、昔より理解が深まってきた気がする

問題

  • カスタムフックがモックできていないので、ずっと読み込み中になる。実装側でAPI見ずに固定値を返すようにしたら欲しいdomがレンダリングされたのでカスタムフック化の間違いではなさそう
// カスタムフック
import {useEffect, useState} from "react";

export const useGetLearnRecords = ({supabase}) => {
    const [isLoading, setIsLoading] = useState(true);
    const [records, setRecords] = useState([]);
    useEffect(()=>{
        supabase.from('learn_records').select('*')
            .then((response) => {
                setRecords(response.data)
                setIsLoading(false)
            })
    },[])

    return {isLoading,records}
}
// テストコード
import { test, vi } from 'vitest'
import {render, screen} from "@testing-library/react";
import {App} from "./App.jsx";

vi.mock("../hooks/useGetLearnRecords",()=>{
    return {
        useGetLearnRecords: vi.fn().mockReturnValue({
            isLoading: false,
            records: [
                {id:1,title:"test",time:1},
                {id:2,title:"test2",time:2},
            ]
        })
    }
})

test('学習記録一覧の文字が表示されている',  () => {

    render(<App />)

    screen.debug()
})

解決

  • ../hooks/useGetLearnRecords のpathが間違っていたのでモックされていなかった
  • ./hooks/useGetLearnRecords として解決

終わりに

  • 実装を書き換えてなど実コード見て一つ一つアプローチしたのが良かったと思う
  • mock化に関しては以下を参考にした
  • 元々カスタムフックにしていなかったが、MSW等を使わなかったのは学習用の実装であり設計をちゃんとしたいという意図が大きいが、できることならソースコードのテストはソースコードレベルだけで検証したい

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