繁体   English   中英

如何在玩笑的异步函数中抛出错误

[英]How to throw error in an async function in jest

我如何测试函数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

现在,我想编写一个测试来测试createTempUsageStatisticsTable(athenaExpress)是否在athenaExpress.query(athenaQueryParam)在模拟实现中抛出错误或拒绝任何合适或有效的承诺时抛出错误,所以我做了

    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();

但是测试似乎没有通过,请帮忙

感谢 James 我让它工作了,但是我稍微调整了他的代码,因为我因为严格相等而出现一些错误,代码如下:

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" });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM