【问题标题】:Testing React component with data provided by custom hook使用自定义钩子提供的数据测试 React 组件
【发布时间】:2020-11-08 20:17:44
【问题描述】:

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

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 作为模块导入,然后像这样模拟响应但没有成功:

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 组件的新手,非常感谢任何输入!

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:

    这行得通:

    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);
      });
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 2023-03-13
      • 2020-02-19
      • 1970-01-01
      • 2021-04-25
      • 2021-04-17
      • 2021-11-17
      • 2021-03-10
      相关资源
      最近更新 更多