gpt4 book ai didi

reactjs - 测试去抖动函数 React - React-testing-library

转载 作者:行者123 更新时间:2023-12-04 08:13:23 25 4
gpt4 key购买 nike

我有以下组件

import React, { useState, useEffect } from 'react';
import { FiSearch } from 'react-icons/fi';
import { useProducts } from '../../hooks';

export default function SearchBar() {
const [query, setQuery] = useState('');
const [debounced, setDebounced] = useState('');

useEffect(() => {
const timeout = setTimeout(() => {
setDebounced(query);
}, 300);
return () => {
clearTimeout(timeout);
};
}, [query]);

const handleChange = (e) => {
e.preventDefault();
setQuery(e.target.value);
};

useProducts(debounced);

return (
<div className="search-form">
<FiSearch className="search-form__icon" />
<input
type="text"
className="search-form__input"
placeholder="Search for brands or shoes..."
onChange={handleChange}
value={query}
/>
</div>
);
}
我想测试是否 useProducts(debounced);实际上在键入后 300 毫秒后调用。遗憾的是,我不知道从哪里开始,希望有人能提供帮助。

最佳答案

首先,我建议您使用 @testing-library/user-event模拟用户在 <input> 上打字元素。其次,你想模拟 useProducts实现断言它在您的测试中被正确调用。

import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import SearchBar from '<path-to-search-bar-component>'; // Update this accordingly
import * as hooks from '<path-to-hooks-file>'; // Update this accordingly

describe('Test <SearchBar />', () => {
it('should call useProducts after 300ms after typing', async () => {
const mockHook = jest.fn();
jest.spyOn(hooks, 'useProducts').mockImplementation(mockHook);
render(<SearchBar />);
const input = screen.getByPlaceholderText('Search for brands or shoes...');
userEvent.type(input, 'A');
expect(mockHook).not.toHaveBeenCalledWith('A'); // It won't be called immediately
await waitFor(() => expect(mockHook).toHaveBeenCalledWith('A'), { timeout: 350 }); // But will get called within 350ms
jest.clearAllMocks();
});
});

关于reactjs - 测试去抖动函数 React - React-testing-library,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65838387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com