javascript - 在 Enzyme 測試中,ref 輸入值預期為空字串,但回傳 undefined
編輯 這裡有一個這個的 Code Sandbox:https://codesandbox.io/s/react-typescript-bt34v
不幸的是,我無法在沙盒中使 Enzyme 配置正常工作,但這個問題的基本代碼都在那裡,點擊按鈕將會列印輸入框的 typeof 值。
我正在嘗試編寫一個測試,用來測試當點擊一個 Button 後,input 元素的值應該如何變化。
當 Button 元件被點擊時,會呼叫這個函式 stopTimer,它會呼叫 useReducer 的 dispatch() 來更新 useReducer 的狀態 store,下面則是按鈕的外觀。
const stopTimer = (): void => {
dispatch({
payload: state.totalSeconds,
type: 'stop',
});
...
<Button handleClick={ stopTimer } />
在另一個檔案中,這就是 useReducer 的樣子,而在其下方是一個 useEffect,當 store 改變時會被呼叫。每當 store 更新時,它會將 ref 的值更新為空字串 ''。
const [store, dispatch] = useReducer(reducer, dashboardStore);
...
useEffect((): void => {
ref.current!.value = '';
}, [store]);
...
<input ref={ref} type='text'></input>
要用 Enzyme 測試這個,我掛載父組件 <Dashboard />,並且給輸入框一個初始值 'hello'。然後我調用 Button 的 handleClick 屬性,該屬性應該會調用 useReducer 的 dispatch 函數,更新 store,然後觸發 useEffect,這應該會將輸入框的值設置為空字串。
我預期這之後輸入的值會是一個空字串,但結果變成了 undefined。
我也在使用 Enzyme 的 debug() 來嘗試驗證 DOM 在不同時間的樣子。當我不調用 Button 的 handleClick,或者如果我沒有調用 wrapper.update(),輸入框的值如預期是 'hello',但是在調用 update() 之後,debug() 顯示輸入框沒有 value 屬性。
it('should contain an empty string when the stop button is clicked', () => {
const wrapper = mount(<Dashboard />);
wrapper.find('input').props().value = 'hello';
act(() => wrapper.find(Button).props().handleClick());
wrapper.update();
console.log(wrapper.find('input').debug());
expect(wrapper.find('input').props().value).toBe('');
});