如何在开玩笑的错误情况下进行测试? 这是我的工作: 我不知道是否存在一种方法来测试这一点。
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;
}
};
答案 0 :(得分:0)
您可以通过以下方式进行操作:
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。
答案 1 :(得分:0)
it ('the fetch fails and throw an error', async () => {
jest.assertions(1);
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().toThrown
相比,它具有以下优势:
it()
中返回Promise即可使其正常工作expect(e).toMatchObject({})
跳过在当前测试用例中不需要的数据)对于缺点-您必须在添加新的断言之后手动更新编号