'How do I test (jest) to expect return?
Using Jest how do I test for return
For example using Lambda:
exports.handler = async (event, context, callback) => {
try {
const orders = await getOrders();
if (!orders) {
console.log("There is no Orders");
return; //<< How do test this?
}
// Something else
} catch (err) {
throw new;
}
};
I am able to test the console log but I also like to test to expect return as well
Currently I am using this in the test:
it("should terminate if there is no order", async () => {
console.log = jest.fn();
let order = await func.handler();
expect(console.log.mock.calls[0][0]).toBe('There is no Orders');
});
Solution 1:[1]
Function with no return will return 'undefined' so you can test for that using not.toBeUndefined();
Solution 2:[2]
Simply expect the value to be undefined:
expect(order).toBeUndefined();
Solution 3:[3]
Necroposting here, but jest now has toReturn and toReturnWith, without and with arguments assessing, accordingly. And also there are toHaveReturned and toHaveReturnedWith to fit new language.
You can use it on spyOn'ed variant of your handler:
it("should terminate if there is no order", async () => {
jest.spyOn(func, "handler")
console.log = jest.fn();
let order = await func.handler();
expect(func.handler).toHaveReturned();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Derek 朕會功夫 |
| Solution 3 | Michael Stets |
