How to handle errors using Flow type hinting and Jest

Viewed 137

I have a class defined like this:

class MyClass{
  constructor(data:Array<any>){
    ...
  }
} 

And a basic test setup in Jest like this:

test('bad args', () => {
  expect(new MyClass()).toThrow();
  expect(new MyClass({})).toThrow();
  expect(new MyClass('string')).toThrow();
});

I would expect these to error as the type hinting does not allow for empty constructor args and expects first arg to be array not an object or string.

Can anyone help explain how I persuade Jest to run the code through Flow and error where types are incorrect?

EDIT: I also have run flow-typed install jest@23.6.0 //correct jest version

1 Answers

The doc states that:

Babel will take your Flow code and strip out any type annotations.

So, flow can help you to find wrong call before build (usually at development time, in ide). And once you run flow in your project - you can catch where is signature mismatch.

After compiling flow annotations are removed, and you have pure javascript.

So, if your constructor accepts any arg, but only array is valid one, you can explicitly state that:

class MyClass {
  constructor(data:*) {
    if (!Array.isArray(data)) {
       throw new Exception('Bad argument');
    }
  }
}

The above codebase will work if you specify data:Array<any> as well, but you'll see errors at compiling time (so you can catch who to blame :) ).

Related