來,今天來看renderHooks這個library吧,大家可以看到昨天的寫法,透過render component的方式去取得hook的value這種方式太不方便,因此今天介紹這一套
'@testing-library/react-hooks'
那接下來把昨天的code進行改寫
import { renderHook, act } from '@testing-library/react-hooks';
import { useChangeName } from '@hooks/useName';
test.only('I want to test useName', () => {
const { result } = renderHook(useChangeName);
expect(result.current.name).toBe('stan');
act(() => {
result.current.setFullName();
});
expect(result.current.name).toBe('stanmaomao');
})
那接下來新增如何傳parms進去hook,來我們看一下這隻API的定義
function renderHook(callback: (prop?: any) => any, options?: RenderHookOptions): RenderHookResult
在RenderHookOptions的選項,我們可以在這邊找到
在這邊我們可以用到initialProps,來傳props進到hook
const { result } = renderHook(useChangeName, {initialProps: {
name: 'good'
}})
那這時我們就可以改寫一下
import { useState } from 'react';
type NameType = {
name: string;
}
export const useChangeName = ({ name: initialName }: NameType) => {
const [name, setName] = useState<string>(initialName);
const setFullName = () => {
setName('stanmaomao');
};
return { name, setFullName };
};
接下來我們測試就改寫成
test.only('useName', () => {
const { result } = renderHook(useChangeName, {
initialProps: {
name: 'good'
}
});
expect(result.current.name).toBe('good');
act(() => {
result.current.setFullName();
});
expect(result.current.name).toBe('stanmaomao');
});
這樣就完成拉!!
明天來學習測試加入Provider