[英]How to save state to localStorage and read it again when the page is reloaded?
[英]How to test if React state is reloaded from localStorage?
我使用 Jest 和 Enzyme 來測試組件,但在重新加載時遇到了問題。 我希望我的組件從 localStorage 中檢索狀態。 我還沒有實現代碼,但測試仍然通過。
it('can preserve todo group', () => {
const wrapper = mount(<TodosContainer />);
wrapper.find('input[name="todo-container-form"]').simulate('change', { target: { value: 'Loy' } });
wrapper.find('button').simulate('click');
// eslint-disable-next-line no-undef
window.location.reload();
/* This is where it should fail without implementation
I didn't add any localStorage code in my component. */
expect(wrapper.find(TodosGroup).first().prop('name')).toMatch('Loy');
});
這是我的組件,其中不重要的部分已被編輯。
const TodosContainer = () => {
const [todosGroups, setTodosGroups] = useState([]);
const [groupName, setGroupName] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const addTodoGroups = (todoGroup: ITodoGroup) => {
setTodosGroups([...todosGroups, todoGroup]);
};
const changeName = (e: React.ChangeEvent<HTMLInputElement>) => {
setGroupName(e.target.value);
};
const handleClick = () => {
if (groupName.length > 0) {
addTodoGroups({ name: groupName, key: Date.now() });
setGroupName('');
setErrorMessage('');
} else {
setErrorMessage('Group name must not be empty');
}
};
return (
<div >
<div >
{errorMessage.length > 0 ? <ErrorMessage css={css`width: 100%`}>{errorMessage}</ErrorMessage> : ''}
<TextInput name="todo-container-form" className="todoGroupName" value={groupName} onChange={changeName} />
<Button type="button" onClick={handleClick}>Add</Button>
</div>
{todosGroups.length > 0 ? todosGroups.map((todoGroup) => (
<div
key={todoGroup.key}
>
<TodosGroup name={todoGroup.name} />
</div>
)) : (
<p>
No todos group
</p>
)}
</div>
);
};
export default TodosContainer;
因為 jest 使用 JSDom 而不是真正的瀏覽器window.location.reload();
什么也沒做。 另外我擔心 jsdom 也沒有實現localStorage
(但很容易嘲笑)
您想確保在重新創建組件后,它從本地存儲中獲取狀態,對嗎?
這樣(在適當的模擬localStorage
)您可以卸載組件並再次安裝它:
wrapper.unmount();
const newOne = mount(<TodosContainer />);
expect(newOne.find(TodosGroup).first().prop('name')).toMatch('Loy');
顯式卸載這里不需要,但我寧願它完全模擬的條件(比如,它會運行componentWillUnmount
/ useEffect
可能是邏輯的一部分)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.