Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly test if the type of the result is a javascript 'function' in jest?

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?

like image 630
ALabrosk Avatar asked Jun 12 '18 13:06

ALabrosk


2 Answers

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");
  });
});
like image 64
PeterDanis Avatar answered Oct 17 '22 15:10

PeterDanis


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.

like image 26
Marnix.hoh Avatar answered Oct 17 '22 15:10

Marnix.hoh