Finding Code Issues with Flow Type Checker

Flow is a static type checker for JavaScript. It can help you identify problems in your code by infering variable types or analyzing static type annotations. For more information, see the Flow documentation.

This recipe describes how to check TestCafe test code with Flow.

Step 1 - Install Flow

To use Flow with TestCafe, you will need two packages.

The first one is the Flow binary responsible for checking your code. Install it locally to the project.

npm install --save-dev flow-bin

With this module, you can introduce type annotations in your code (or let Flow infer the types implicitly) and run code checks.

However, this only works for your test code. Flow will still treat TestCafe API as untyped and imply that all API members has the type any.

To provide type information for third-party libraries (including TestCafe), Flow uses a special module - flow-typed. Install it globally.

npm install -g flow-typed

Step 2 - Initialize Flow

First, open package.json and configure npm to run Flow.

"scripts": {
    "flow": "flow"
}

Run the following command to initialize Flow with default configuration.

npm run flow init

Install the TestCafe library definition to provide type information for TestCafe API.

flow-typed install testcafe@0.x.x

Step 3 - Prepare Your Test Files

At the beginning of each test file that you wish to check with Flow, place the following comment.

//@flow

You can optionally provide type annotations for variables in test code.

//@flow

fixture `My Fixture`
    .page `https://example.com`;

test('My Test', async t => {
    function foo(bar: number): string {
        // ...
    };

    var n: number;

    // ...

    n = "foo"; // <- error
});

Now when you perform an operation that violates the type annotations, Flow will raise an error.

Step 4 - Check Test Code

To run the check, simply call Flow with no parameters.

npm run flow