Featured image of post Firebase Cloud Functionsでjestを導入するまでの道のり

Firebase Cloud Functionsでjestを導入するまでの道のり

Twitter ツイート Hatena Bookmark ブックマーク

最近Firebase Cloud Functionsでお仕事をしているのですが、jestを入れたちょっとハマったのでその記録です。

環境について

firebase initで全力でenterfunctionsを用意しました。 一応こんな感じでTypeScriptでコード書いててeslintは導入済みの想定です。

まずはjestを入れる

1
yarn add --dev jest @types/jest ts-jest

こんな感じでいれました。

テスト用のコードはビルドしたくないのでtsconfigの設定を変更する

今回はテストは __test__ ディレクトリに入れる用にしているのでexclude__test__はビルド対象から外すようにします。

1
2
3
4
5
// tsconfig.json
...
"exclude": [
  "src/**/__test__/*.ts"
]

eslintでエラーになった

1
2
$ yarn jest
  0:0  error  Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.

どうやらtscofnig.jsonで、testファイルをexcludeしたのが原因らしい。
しかしtestコードはbuildしたくない。。

jest用のtsconfig作って解決した

tsconfig.jest.json

1
2
3
4
{
  "extends": "./tsconfig.json",
  "exclude": []
}

このようにtsconfig.jest.jsonを作って .eslintrc.jsを以下のように修正した。

1
2
3
4
parserOptions: {
  project: "tsconfig.jest.json",
  sourceType: "module",
},

これでうまく行った。

最後にnpm scriptsにtest: 'jest'って書いてnpm run testとかできるようにした。

ついでだからGithub Actionsでjest動かすようにした

こんな感じに書いた。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
name: pull request

on: [pull_request]

jobs:
  test:
    runs-on: ubuntu-18.04
    steps:
      - uses: actions/checkout@v2
      - name: setup Node
        uses: actions/setup-node@v2-beta
        with:
          node-version: ’12’
      - name: Build
        run: cd functions && yarn
      - name: Lint
        run: cd functions && yarn lint
      - name: Jest
        run: cd functions 

でもなぜかエラーになった。
とおもったらjest.config.jsがignoreされててコミットできてなかった…。
原因はfunctions/.giignoreの記述にあった。

1
**/*.js

このようにjsファイルがコミットされないようになっていたのでjest.config.jsもコミットされてなかった。。。
なので下記のように修正。

1
2
**/*.js
!jest.config.js

まとめ

  • yarn add –dev jest @types/jest ts-jest
  • tsconfig.jsonでexcludeを src/**/__test__/*.ts
  • tsconfig.jest.jsonでexcludeを[]
  • .eslintrc.jsでparserOptions.projectでtsconfig.jest.jsonを指定
comments powered by Disqus
Built with Hugo
テーマ StackJimmy によって設計されています。