gpt4 book ai didi

react-native - 我如何用 throw e Jest 进行测试?

转载 作者:行者123 更新时间:2023-12-03 23:11:00 24 4
gpt4 key购买 nike

我如何在 Jest 错误情况下进行测试?
这就是我所做的:
我不知道是否存在一种方法来测试这个。

it ('the fetch fails and throw an error', async () => {
let response = {
status: 400,
body:
{
base : "RON",
date: "2019-08-01",
rates: {"error": 'error'}
}
};
fetch.mockReject(response)
try {
await fetchData();
} catch (e) {
expect(e).toEqual(response);
expect(await fetchData()).rejects.toThrow(e);
}
});

这是代码:
 fetchData = async () => {
try {
const response = await fetch('https://api.exo/latest?base=RON');
const data = await response.json();
return data;
} catch (e) {
throw e;
}
};

最佳答案

您可以通过以下方式进行操作:

async function throws () {
throw new Error('error')
}

test('promise throws', async () => {
await expect(throws()).rejects.toThrow()
})

test('the fetch fails with an error', async () => {
await expect(throws()).rejects.toThrow('error');
});

test('the fetch fails with an error', () => {
return expect(throws()).rejects.toMatch('error');
});

阅读更多 docs .

关于react-native - 我如何用 throw e Jest 进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57309678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com