Setting up Bitbucket Pipelines with proper caching of NPM and Cypress

Back to Cypress blog

This is a guest post from Ondřej Janošík, co-owner of Notum Technologies, full-stack developer and clean code enthusiast based in the Czech Republic.

Bitbucket Pipelines & Deployments is integrated CI/CD for Bitbucket Cloud that’s trivial to set up, automating your code from test to production (at least that’s what the official site says). However, setting up your pipelines with right commands and right caching in order to be as fast as possible requires some time. In this article, I am going to show how it can be done.

Cycle showing plan, code, build, test, release, deploy, operate, measure

TL;DR

If you came here just to see the configuration without explanation here it is:

image: node:10.8.0
options:
  max-time: 30
pipelines:
  default:
  - step:
      name: Install, build and tests
      caches:
        - npm
      script:
        - npm ci
        - npm run build
        - npm run test
  - step:
      name: E2E tests
      caches:
        - npm
        - cypress
      image: cypress/base:10
      script:
        - npm ci
        - npm run e2e
definitions:
  caches:
    npm: $HOME/.npm
    cypress: $HOME/.cache/Cypress

Configuration

Image

In this configuration, we are using the docker image node:10.8.0. If you want to use a different one, one can choose one from here.

Options section

This section is completely optional, meaning you can skip this part. I am using this part to set the maximum length of the pipeline. Without this time to time something bad can happen and your pipeline can run forever.

Pipelines section

The pipelines section is the main section where you specify each step. We have two steps. In the first, we are installing packages, running tests and building the application. We are using NPM CI — a new command in NPM that has been created especially for this use case (you can read more here). In the second step, we are running the E2E tests using Cypress. Cypress requires us to use a different image so we need to create a special step for that.

Cache definitions

Using a cache can help us to save a lot of build minutes. We are caching two folders — $HOME/.npm & $HOME/.cache/Cypress. The first one is boosting NPM CI command and the second one is holding the Cypress binary.

Summary

Bitbucket Pipelines is a great tool for CI/CD. This feature is paid based on the number of build minutes so I suggest you using NPM CI and have a look at the cache section in order to save your time and money :)