I have a Class module that I'm trying to unit test with Jest. Specifically an async method. I want to test a branch in the method where an error is thrown in a try, caught in the catch, and then rethrown from the catch. Here's a slimmed down example of the structure.
myClass.js
const helper = require("helper");
module.exports = class myClass {
constructor() {
...
}
async myMethod() {
try {
const response = await helper.getSomeObject();
if (response.someArray.length == 0)
throw new Error("Whoops!");
return response;
}
catch (err) {
...
throw err;
}
}
}
myClass.test.js (Attempt #1)
const myClass = require("myClass");
const helper = require("helper");
describe("Testing myClass", () => {
test("myMethod should throw error", async () => {
helper.getSomeObject = jest.fn().mockResolvedValueOnce({someArray: []});
const mc = new myClass();
const response = await mc.myMethod();
expect(response).rejects.toEqual(Error("Whoops!"));
});
});
myClass.test.js (Attempt #2)
const myClass = require("myClass");
const helper = require("helper");
describe("Testing myClass", () => {
test("myMethod should throw error", async () => {
helper.getSomeObject = jest.fn().mockResolvedValueOnce({someArray: []});
const mc = new myClass();
await mc.myMethod();
expect(async () => await mc.MyMethod()).toThrow("Whoops!");
});
});
Obviously, I don't know what I'm doing. In either attempt, the unit test fails, but it doesn't seem to fail when checking the expect statement. It seems like the expect statement isn't even being called. All I'm seeing in the output is the error message "Whoops!" and that's it.
I'd greatly appreciate any help. Thank you!
Figured it out! I got it to work with the following.
myClass.test.js (Attempt #3)
const myClass = require("myClass");
const helper = require("helper");
describe("Testing myClass", () => {
test("myMethod should throw error", async () => {
helper.getSomeObject = jest.fn().mockResolvedValueOnce({someArray: []});
try {
const mc = new myClass();
await mc.myMethod();
}
catch (err) {
expect(err).toEqual(Error("Whoops!"));
}
});
});