繁体   English   中英

使用自定义钩子提供的数据测试 React 组件

[英]Testing React component with data provided by custom hook

我创建了这个自定义钩子来获取数据:

const useSuggestionsApi = () => {
  const [data, setData] = useState({ suggestions: [] });
  const [url, setUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
 
  useEffect(() => {
    const fetchData = () => {
      setError(false);
      setLoading(true);
      if(url) {
        fetch(url).then((res) => {
          if (res.status !== 200) {
            console.error(`It seems there was an problem fetching the result. Status Code: ${res.status}`)
            return;
          }
          res.json().then((fetchedData) => {
            setData(fetchedData)
          })
        }).catch(() => {
          setError(true)
        })
        setLoading(false);
      };
      }

    fetchData();
  }, [url]);
 
  return [{ data, loading, error }, setUrl];
}

export default useSuggestionsApi;

它在此组件中用于呈现响应( suggestions )。

const SearchSuggestions = ({ query, setQuery}) => {
  const [{ data }, doFetch] = useSuggestionsApi(); 
  const { suggestions } = data;

  useEffect(() => {
    const encodedURI = encodeURI(`http://localhost:3000/search?q=${query}`);
    doFetch(encodedURI);
  }, [doFetch, query]);

  return (
    <div className="search-suggestions__container">
      <ul className="search-suggestions__list">
        {suggestions.map((suggestion) => {
          return (
          <li className="search-suggestions__list-item" key={uuid()}>
            <span>
              {suggestion.searchterm}
            </span>
          </li>
          )
        })}
      </ul>
    </div>
 );
};

export default SearchSuggestions;

现在我想为SearchSuggestions组件编写一些单元测试,但我不知道如何模拟useSuggestionApi返回的数据。 我尝试将useSuggestionApi作为模块导入,然后像这样useSuggestionApi响应但没有成功:

describe('SearchSuggestions', () => {
  const wrapper = shallow(<SearchSuggestions/>)

  it('test if correct amount of list-item elements are rendered', () => {
    jest.mock("../hooks/useSuggestionsApi", () => ({
      useSuggestionsApi: () => mockResponse
    }));
    expect(wrapper.find('.search-suggestions__list').children()).toHaveLength(mockResponse.data.suggestions.length);
  });
})

我是测试 React 组件的新手,非常感谢任何输入!

这有效:

jest.mock('../hooks/useSuggestionsApi', () => {
  return jest.fn(() => [{data: mockResponse}, jest.fn()]
  )
})
describe('SearchSuggestions', () => {
  const wrapper = shallow(<SearchSuggestions query="jas"/>)

  it('correct amount of list-items gets rendered according to fetched data', () => {
    expect(wrapper.find('.search-suggestions__list').children()).toHaveLength(mockResponse.suggestions.length);
  });
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM