Search code examples
mysqlnode.jsgitlabgitlab-cigitlab-ci-runner

Run Unit Tests in gitlab CI connecting to a real database


I want to run unit tests on Gitlab CI. I am using nodejs, jest, mysql. I am trying to run mysql on the CI to connect to the same server while running the unit tests. I am inserting some dummy data as well to keep it simple.

When I run the tests on local the test runs with some errors, but the test passes with some post run errors. However, on gitlab CI the test script is not able to connect to the mysql service.

Following is my gitlab-ci.yml

services:
  - mysql:8.0
variables:
  MYSQL_DATABASE: test_database
  MYSQL_ROOT_PASSWORD: root

stages:
  - build
build:
  stage: build
  services:
    - mysql
  only:
    refs:
      - master
  image: klvenky/node-12-alpine-docker:latest
  cache:
    key: "$CI_COMMIT_REF_SLUG"
    paths:
      - .yarn
  script:
    - yarn config set cache-folder $PWD/.yarn
    - export FROM_GIT_URL="git.ssh://git"
    - export TO_GIT_URL="https://gitlab-ci-token:$CI_JOB_TOKEN"
    - sed -i "s#$FROM_GIT_URL#$TO_GIT_URL#" package.json yarn.lock
    - yarn --ignore-optional --pure-lockfile --prefer-offline
    - yarn test

My Repo is hosted on Gitlab here. Please let me know what is going wrong.


Solution

  • The error message regarding mysql in your pipeline states:

    ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

    The node package mysqljs doesn't support the default authentication method of MySQL 8.

    You can find the answer and possible solutions here.

    There is also a problem with your services definition in the gitlab-ci file. As mentionend in the comments, you have specified the service twice with the same name. Defining it only once (with the correct command substitution) should work:

    services:
      - mysql:8.0
        alias: mysql
        command: [ "--default-authentication-plugin=mysql_native_password" ]
    
    variables:
      MYSQL_DATABASE: test_database
      MYSQL_ROOT_PASSWORD: root
    
    stages:
      - build
    build:
      stage: build
      only:
        refs:
          - master
      image: klvenky/node-12-alpine-docker:latest
      cache:
        key: "$CI_COMMIT_REF_SLUG"
        paths:
          - .yarn
      script:
        - yarn config set cache-folder $PWD/.yarn
        - export FROM_GIT_URL="git.ssh://git"
        - export TO_GIT_URL="https://gitlab-ci-token:$CI_JOB_TOKEN"
        - sed -i "s#$FROM_GIT_URL#$TO_GIT_URL#" package.json yarn.lock
        - yarn --ignore-optional --pure-lockfile --prefer-offline
        - yarn test