And*_*eea 5 jestjs react-native
如何在玩笑错误情况下进行测试?这就是我所做的:我不知道是否存在如何测试它的方法。
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);
}
});
Run Code Online (Sandbox Code Playgroud)
这是代码:
fetchData = async () => {
try {
const response = await fetch('https://api.exo/latest?base=RON');
const data = await response.json();
return data;
} catch (e) {
throw e;
}
};
Run Code Online (Sandbox Code Playgroud)
it ('the fetch fails and throw an error', async () => {
expect.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);
}
});
Run Code Online (Sandbox Code Playgroud)
一旦没有抛出异常,测试就会失败。它具有以下优点expect().toThrown:
it()使其工作expect(e).toMatchObject({})跳过当前测试用例中您不关心的一些数据)至于缺点 - 添加新断言后必须手动更新数字
| 归档时间: |
|
| 查看次数: |
4361 次 |
| 最近记录: |