LoginSignup
9
5

More than 3 years have passed since last update.

CypressでTypescriptを使いたいが、Custom Commandsをsupport/commands.tsにすると色々崩れる時の解決方法

Last updated at Posted at 2019-09-22

"cypress": "^3.4.1"現在

Cypressのテストを.tsで書くのは簡単

Transpiling TypeScript test filesにあるように

  1. tsconfig.jsonを書く
  2. テストファイルを.tsにする
  3. テストをTypescriptで書く

これだけで良い

CypressのCustom CommandsもTypescriptで書きたい

上の状態でsupport/commands.jsをJavascriptのまま書くなら何も問題が無いが、これすらもsupport/commands.tsとTypescriptで書こうとすると色々問題が出てくる

直接的な解決方法はこの例にあるrepoを見れば分かるが、流れとしては

  1. Cypressは素の状態ではsupport/index.jsを読み込む
  2. support/index.jssupport/commands.jsを読み込む
  3. これによりCustom Commandsが使えるようになる

なので

  1. support/commands.jssupport/commands.tsにするには
  2. support/index.jssupport/index.tsにしないといけない
  3. support/index.tsにしたのなら、Cypressにsupport/index.tsを読み込むように指示しないといけない
  4. この為、configのsupportFileを変更しないといけない
  5. 更にはこれらのtsをトランスパイル出来るように色々インストールしておかないといけない

解決方法

plugins/index.jsに何か追加していたなら、事前にplugins/index.jsはバックアップしておいた方が良い
@bahmutov/add-typescript-to-cypressがざっくり上書きする!

  1. yarn add -D @babel/core @babel/preset-env @bahmutov/add-typescript-to-cypress babel-loader typescript webpack を追加でインストール
  2. plugins/index.jsの内容が変わっているので、追加内容があったのなら編集
  3. cypress.jsonに"supportFile": "cypress/support/index.ts"を追加(パスはcypress.jsonの位置から見て相対で)
  4. support/index.jssupport/index.ts
  5. support/commands.jssupport/commands.ts
  6. support/commands.ts内にdeclare globalを記載する
  7. support/commands.ts内にexport {}を記載する

後は通常通りcypressを走らせられるし、IntelliSenseも効く

9
5
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
9
5