3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

環境変数を利用したコードのCI process.env.hogeってどうすればいいの?

Last updated at Posted at 2021-06-03

はじめに

Node.js(Express)でWeb APIをCallする際のAPI Keyを環境変数にしていた場合に、GitHub ActionsでJestによるCIを回そうとして躓いたのでその時の解決方法を備忘録として残しておく。

どんなテストをしようとしたか?

Node.js(Express)で以下のようなソースコードを実装していて、これのAPIテスト(あえて今回はモックにしていない)をJest×Supertestで実装し、それをCI上で回そうとしていた。
テスト対象のソースコード(抜粋)は以下。
${process.env.COUNTRYSTATECITY_API_KRY}の部分で環境変数を使っている。

controller.js
const axios = require('axios').default;

// dotenv
const dotenv = require('dotenv')
dotenv.config();

// instance for get countries and cities
const instance = axios.create({
    baseURL: 'https://api.countrystatecity.in/v1/',
    timeout: 3000,
    headers: { 'X-CSCAPI-KEY': `${process.env.COUNTRYSTATECITY_API_KRY}` }
})

const allCountries = async (req, res) => {
    try {
        const countries = await instance.get('countries')
        res.send({ countries: countries.data })
    } catch (error) {
        errorHandler(res, error)
    }
}

// 省略

テストコードは以下。

test.js
const request = require('supertest')
const app = require('../../../src/server/app')

describe('Get Endpoints (not mocking)', () => {
    it('/allCountries', async () => {
        const res = await request(app).get('/allCountries')
        expect(res.status).toEqual(200)
        expect(res.body.countries[0].name).toEqual('Afghanistan')
    })
// 省略
})

ソースコード全体は以下。

※Jest×SupertestでのNode.js(Express)のAPIテストについてはこちらの記事を参照

解決方法(どうするのか?)

GitHubのSecretsに環境変数の値を登録し、GitHub Actionsのパイプライン(yaml)でそれを読み込む。
yamlの方は以下のようになり、envコンテキストCOUNTRYSTATECITY_API_KRY: ${{ secrets.COUNTRYSTATECITY_API_KRY }}を宣言する事で、Secretsに登録した値がsecrets.COUNTRYSTATECITY_API_KRYで取得でき、環境変数をCIのRunnerが動く環境に設定できる。

jest.yml
name: Testing by Jest

on:
  push:
    branches:
      - "**"

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      - name: package-lockより環境構築
        run: npm ci

      - name: テスト実行
        env:
          GEO_NAME_USERNAME: ${{ secrets.GEO_NAME_USERNAME }}
          WAETHERBIT_API_KEY: ${{ secrets.WAETHERBIT_API_KEY }}
          PIXABAY_API_KEY: ${{ secrets.PIXABAY_API_KEY }}
          COUNTRYSTATECITY_API_KRY: ${{ secrets.COUNTRYSTATECITY_API_KRY }}
        run: npm test

GitHub ActionsのSecretsはこんな感じになっており、secrets.で取得するkeyで値を登録してある。詳細は「ソースコード全体は以下」のリンクのリポジトリを参照。
image.png

実際のJob

参考文献

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?