Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock 2 fetch calls with jest?

I am trying to test a component that makes 2 fetch calls inside the used hook:

  useEffect(() => {
    let viewCodePromise = getCode(id);
    viewCodePromise.then(data => {
      if (data.success === 1) {
        setCode(data.code);
      } else {
        setError(data.error);
      }
    });

    let getCommentsPromise = getComments(id);
    getCommentsPromise.then(data => {
      if (data.success === 1) {
        setComments(data.comments);
      } else {
        setError(data.error);
      }
    });
  }, []);

the functions getCode() and getComments() are making the fetch calls. How can I mock tests with jest both fetch calls?

like image 255
Samoila Andrei Avatar asked Nov 23 '25 07:11

Samoila Andrei


1 Answers

You could use the jest mock function.

const getCode = jest.fn(() =>
    Promise.resolve({
        success: 1
    })
)

const getComments = jest.fn(() =>
    Promise.resolve({
        success: 1
    })
)
like image 192
ecoplaneteer Avatar answered Nov 24 '25 21:11

ecoplaneteer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!