SaltyCrane Blog — Notes on JavaScript and web development

Next.js Cypress GitLab CI example

This is an example Next.js project that runs a Cypress test in Docker using a GitLab CI pipeline. It also uses the GitLab Container Registry for caching purposes.

.gitlab-ci.yml

variables:
  DOCKER_TLS_CERTDIR: "/certs"

stages:
  - test

test-cypress:
  stage: test
  image: docker:latest
  services:
    - docker:dind
  variables:
    IMAGE_TAG: $CI_REGISTRY_IMAGE:latest
  script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker pull $IMAGE_TAG || true
    - docker build --cache-from $IMAGE_TAG -t $IMAGE_TAG .
    - docker push $IMAGE_TAG
    - docker run $IMAGE_TAG npm run cy:citest

Dockerfile

This uses the official Cypress Docker image (Dockerfile).

FROM cypress/base:14.16.0

WORKDIR /app
# run npm install before adding app code for better Docker caching
# https://semaphoreci.com/docs/docker/docker-layer-caching.html
COPY ./package.json /app
COPY ./package-lock.json /app
# CI=true suppresses Cypress progress log spam
RUN CI=true npm ci
COPY . /app
RUN npm run build

package.json

{
  "scripts": {
    "build": "next build",
    "cy:citest": "start-server-and-test start http://localhost:3000 cy:run",
    "cy:run": "cypress run",
    "dev": "next",
    "start": "next start"
  },
  "dependencies": {
    "next": "^10.0.9",
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "cypress": "^6.8.0",
    "start-server-and-test": "^1.12.1"
  }
}

cypress/integration/index_spec.js

describe("index page", () => {
  it("loads successfully", () => {
    cy.visit("http://localhost:3000");
    cy.contains("Index");
  });
});

References

Comments