Reputation: 134
How do i test if the function createTempUsageStatisticsTable(athenaExpress)
throws an error and also to test if createTempUsageStatisticsTable(athenaExpress)
throws error because the function athenaExpress.query(athenaQueryParam)
throws an error (Using Jest) ? (Assume filename to be 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
Now,I want to write a test to test if createTempUsageStatisticsTable(athenaExpress)
throws an error when athenaExpress.query(athenaQueryParam)
throws an error or rejects a promise in a mock implementation whichever is suitable or works,so i did
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();
However tests do not seem to pass please help
Thanks to James i got it working,However i slightly tweaked his code as i was getting some error due to strict equal,The code is as follows:
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);
});
Upvotes: 2
Views: 15240
Reputation: 82136
Depending on how athenaExpress
is exported, you can mock query
to throw and then test for the existence of said by leveraging rejects
e.g.
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" });
});
Upvotes: 4