jest: failing commits on failing tests

2021-01-18

 | 

~2 min read

 | 

365 words

CI/CD pipelines are designed to ensure that no broken code reaches the main branch.However, running all of the tests and compiling a project can take a long time. Having an engineer monitor that process can feel like dead / unproductive time. Worse, however, is the situation where the CI/CD pipeline does its job and finds that a test fails because of a commit while the engineer moved on to work on something else. Now they will have to context switch back to the work that failed to try to fix it.

Wouldn’t it be so much better if we could avoid this problem altogether? Well, at least in a limited set of circumstances, we can.

The idea is very similar to automating linting with husky and lint-staged, except that instead of (or in addition to) linting, we’ll be running our test suite.

For the purposes of this post, I’ll be demonstrating how to configure this with Jest, my preferred test runner.

Using the same configuration as in the post on automating linting, we can make just one slight modification to add tests:

{
    "*.+(js|ts|tsx)": ["eslint"],
    "**/*.+(js|json|ts|tsx)": [
        "prettier --write",
        "jest --findRelatedTests" //highlight-line
    ]
}
{
    "hooks": {
        "pre-commit": "lint-staged && npm run build"
    }
}

As long as Jest is configured in this project, now any time an engineer attempts to commit code we’ll run related tests.

Wrap Up

Thanks to husky’s pre-commit hook executing lint-staged which itself is configured to execute jest for any .js, .json, .ts, or .tsx files, we have automated testing at the local level.

Because test suites can grow and take a long time to run, even with a runner as efficient as Jest, we have specified only to run tests related to the change set (thanks to the --findRelatedTests flag).

While this won’t necessarily ensure that a CI/CD pipeline never finds a test failure that is not found locally, it will help avoid the situation, keeping engineers productive.

It’s a small cost up front to avoid a much larger pain down the road. The fact that it’s automated and doesn’t rely on an engineer remembering to run the tests makes it all the sweeter.


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!