【问题标题】:React Jest:- node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */);React Jest:- node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */);
【发布时间】:2022-05-05 23:20:48
【问题描述】:

我有下面的反应代码。

useEffect(() => {
        (async () => {
            await httpClient
                .get(`${config.resourceServerUrl}/inventory/`)
                .then((response) => {
                    setSponsor(response.data.sponsor);
                    setAddress(response.data.address);
                    setPhaseOfTrial(response.data.phaseOfTrial);
                })
                .catch((error) => {
                    alert(error);
                });
        })();
    }, []);

此代码成功运行。唯一的问题是,它在开玩笑的测试用例中失败了。

describe('ListInventory', () => {
    it('should render successfully', () => {
        const { baseElement } = render(<ListInventory />);
        expect(baseElement).toBeTruthy();
    });
});

以下是错误。

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read properties of undefined (reading 'get')".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

我已经在使用catch 块。代码有什么问题?你能帮我做同样的事情吗?

【问题讨论】:

    标签: javascript reactjs promise jestjs callback


    【解决方案1】:

    尝试使用 try-catch 块处理 Promise,如下所示:

      useEffect(() => {
        (async () => {
          try {
            let response = await httpClient.get(
              `${config.resourceServerUrl}/inventory/`
            );
            setSponsor(response.data.sponsor);
            setAddress(response.data.address);
            setPhaseOfTrial(response.data.phaseOfTrial);
          } catch(error) {
            alert(error);
          }
        })();
      }, []);
    

      useEffect(() => {
        (async () => {
            let response = await httpClient.get(
              `${config.resourceServerUrl}/inventory/`
            );
            setSponsor(response.data.sponsor);
            setAddress(response.data.address);
            setPhaseOfTrial(response.data.phaseOfTrial);
        })().catch(e=>alert(e));
      }, []);
    

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题。

      此问题可能是由于 response.data 旁边的对象之一未定义。 添加条件来检查它的存在。

      这解决了我的问题

      【讨论】:

      猜你喜欢
      • 2022-11-17
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2022-10-30
      • 1970-01-01
      • 2015-07-06
      • 2020-09-08
      • 1970-01-01
      相关资源
      最近更新 更多