我有下面的代码在React。
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);
});
})();
}, []);
此代码成功运行。唯一的问题是,它在jest测试用例中失败。
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
块了。代码有什么问题吗?你能帮我解决吗?
3条答案
按热度按时间pu3pd22g1#
尝试使用try-catch块处理该承诺,如下所示:
或
sy5wg1nm2#
你应该让你的测试异步,因为你的代码中有异步调用:
lxkprmvk3#
我遇到了类似的问题。
此问题可能是由于www.example.com旁边的某个对象response.data未定义。请添加条件以检查其是否存在。
这解决了我的问题