0

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!

1 Answer 1

1

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);
  });
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.