简体   繁体   English

如何用玩笑模拟 2 个 fetch 调用?

[英]How to mock 2 fetch calls with jest?

I am trying to test a component that makes 2 fetch calls inside the used hook:我正在尝试测试一个在使用的钩子内进行 2 次 fetch 调用的组件:

  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.函数 getCode() 和 getComments() 正在进行提取调用。 How can I mock tests with jest both fetch calls?我怎样才能用 jest 两个 fetch 调用来模拟测试?

You could use the jest mock function.您可以使用 jest 模拟功能。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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