如何测试函数 createTempUsageStatisticsTable(athenaExpress)
是否引发错误,以及测试 createTempUsageStatisticsTable(athenaExpress)
是否因函数 athenaExpress. query(athenaQueryParam)
抛出错误(使用 Jest)? (假设文件名为 index.js
)
async function createTempUsageStatisticsTable(athenaExpress) {
let athenaQueryParam = {
sql: getSqlQueries.CREATE_DEVICE_USAGE_STATS_TEMP_TABLE_QUERY,
db: "testdb"
};
await athenaExpress.query(athenaQueryParam);
}
exportFunctions={createTempUsageStatisticsTable:createTempUsageStatisticsTable}
module.exports=exportFunctions
现在,我想编写一个测试来测试当 athenaExpress.query(athenaQueryParam)
抛出错误或拒绝 promise 时 createTempUsageStatisticsTable(athenaExpress)
是否抛出错误一个模拟实现,无论是合适的还是有效的,所以我做了
const confError = new Error('network error');
athenaExpress.query = jest.fn().mockImplementationOnce(() => {
throw new Error(confError); // tried this
promise.reject(confError);
})
index.configureAthenaExpress();
expect(index.configureAthenaExpress).toThrow();
但是测试似乎没有通过,请帮忙
感谢詹姆斯,我让它工作了,但是我稍微调整了他的代码,因为我由于严格相等而遇到了一些错误,代码如下:
test("createTempUsageStatisticsTable throws an exception if
athenaExpress.query fails()", async () => {
const creaError=new Error("network error")
athenaExpress=configureAthenaExpress();
athenaExpress.query.mockRejectedValueOnce(creaError);
await expect(createTempUsageStatisticsTable(athenaExpress)).rejects.toBe(creaError);
});
最佳答案
根据 athenaExpress
的导出方式,您可以模拟 query
来抛出,然后利用 rejects
测试所述内容是否存在。例如
const createTempUsageStatisticsTable = require("./createTempUsageStatisticsTable");
const athenaExpress = require("./athenaExpress");
jest.mock("./athenaExpress");
test("createTempUsageStatisticsTable throws if query fails", async () => {
athenaExpress.query.mockRejectedValueOnce(new Error("network error"));
await expect(createTempUsageStatisticsTable(athenaExpress)).rejects.toMatchObject({ message: "network error" });
});
关于javascript - 如何在 Jest 中的异步函数中抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59901803/