はじめに
- 久々にちゃんとテストコードを手書きしたけど、昔より理解が深まってきた気がする
問題
- カスタムフックがモックできていないので、ずっと読み込み中になる。実装側で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等を使わなかったのは学習用の実装であり設計をちゃんとしたいという意図が大きいが、できることならソースコードのテストはソースコードレベルだけで検証したい
