Mock global fetch with TypeScript getting error "is not assignable to type..."
Asked Answered
J

1

5

I'm getting this error below on the "global.fetch" part and I'm not sure why. I feel like I'm doing it a pretty standard way..what am I missing? I'm open to anything even libraries.. I'm just trying to learn how to test my Component with React Testing Library that fetches data and renders a list and I'm having so much trouble...

Thank you for anyone that helps

TS2322: Type 'Mock<Promise<{ json: () => Promise<Data[]>; }>, []>'
is not assignable to type '(input: RequestInfo | URL, init?: RequestInit) => Promise'.   Type 'Promise<{ json: () => Promise<Data[]>; }>' is not assignable to type 'Promise'.     Type '{ json: () => Promise<Data[]>; }' is missing the following properties from type 'Response': headers, ok, redirected, status, and 10 more.

I'm seeing that the universal way to mock global.fetch is like so:

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve(....data here...),
  })
);

My component looks like this:

const SomeComponent = () => {
  const [dataList, setDataList] = useState<Data[]>([]);  

  const fetchdataList = async () => {
    const response = await fetch(URL);
    const json = await response.json();    
    setDataList(json);
  }

  useEffect(() => {
    fetchdataList();
  }, []);
}
  useEffect(() => {
    fetchNpos();
  }, []);
Jello answered 15/9, 2022 at 2:51 Comment(0)
J
8
global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({....}),
  }),
) as jest.Mock;  // <-- adding this solved the issue
Jello answered 15/9, 2022 at 3:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.