How to properly test (using jest) whether the result is an actual JavaScript function?
describe('', () => {
it('test', () => {
const theResult = somethingThatReturnsAFunction();
// how to check if theResult is a function
});
});
The only solution I found is by using typeof
like this:
expect(typeof handledException === 'function').toEqual(true);
Is this the correct approach?
You can use toBe
matcher to check whether result of typeof
operator is function
, please see example:
describe("", () => {
it("test", () => {
const somethingThatReturnsAFunction = () => () => {};
const theResult = somethingThatReturnsAFunction();
expect(typeof theResult).toBe("function");
});
});
Jest offers a nice way to check the type of a supplied value.
You can use .toEqual(expect.any(<Constructor>))
to check if the provided value is of the constructor's type:
describe('', () => {
it('test', () => {
const theResult = somethingThatReturnsAFunction()
expect(theResult).toEqual(expect.any(Function))
})
})
Other examples of constructors are: String
& Number
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With