简体   繁体   中英

Testing React component with data provided by custom hook

I have created this custom hook to fetch data:

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;

It used used in this component to render the response ( 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;

Now I would like to write some unit test for the SearchSuggestions component but I am lost on how to mock the returned data from useSuggestionApi . I tried importing useSuggestionApi as a module and then mocking the response like this but with no success:

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

I am new to testing React components so very grateful for any input!

This works:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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