LoginSignup
1
1

More than 3 years have passed since last update.

Writing Cypress tests in TypeScript

Last updated at Posted at 2021-01-05

Typescript で Cypress testを書く

はじめに

Typescript で Webアプリケーションを書いている際に、テストプログラムが必要になる。
比較検討した結果Cypressが何かと使い勝手が良いようなので使うことにした。
なお、当方は開発環境をUbuntu 20.04 LTS on WSL2 かつ vscodeで行っているのでこの環境で動かす為の手順を合わせて記載する。

環境要件

  • OS: WSL2上で動作するUbuntsu 20.04LTS
  • 使用エディタ VScode
  • パッケージ管理には yarn を使用

この記事の目標

  • Cypress を動かすためのWSL2(Ubuntu 20.04LTS)の環境作り
  • Cypress のインストール完了
  • Cypress の起動
  • Typescriptによるテストコードの作成・実行

前提条件

  • 適当なtypescript projectが存在し起動する

作業手順

WSL2の環境作り

Cypressには CLIがあるので必ずしもXは必要では無いが、
あった方が便利なのでX環境も含めて環境作りとする。

X環境作り

Xサーバインストール

まずは母艦(Windows)側の環境作りが必要なのでそちらから手がける。
VcXsrvをダウンロードしインストールする。
exe形式で配布されているのでインストール作業に手間取る人は居ないと思う。
というか、そのレベルで詰まるようであれば諦めろ。無理だ。

初期設定
  • Display Settings
    • Multiple win windows を選択

image.png

  • Select how to start clients
    • Start no clientを選択

image.png

  • Extra Settings
    • Additional parameters for VcXsrv-acを追記

image.png

次の画面でsave config とあるがそこはお好みで。

X関連パッケージのインストール
# sudo apt install x11-apps
# export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2; exit;}'):0
# xeyes

正しく設定されていれば目玉が出る。なお、
export DISPLAY は今後も使うので .bashrc辺りにでも書いておくと今後が楽になる。

日本語フォントの追加

WSL2、素のUbuntuは日本語フォントが入っていないので殆どがフォント無しになってしまう。
従ってOSのフォントを使えるようにしてしまう方が良い。

$ sudo vim /etc/fonts/local.conf
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
    <dir>/mnt/c/Windows/Fonts</dir>
</fontconfig>

なお、Dockerで使う場合は母艦のフォントをマウント。と言うわけには行かないのでこんな風に。

RUN apt-get update
RUN apt-get install -y locales locales-all
RUN apt-get remove fonts-vlgothic
RUN apt-get install -y fonts-vlgothic
RUN locale-gen ja_JP.UTF-8
ENV LANG ja_JP.UTF-8
ENV LC_CTYPE ja_JP.UTF-8
RUN localedef -f UTF-8 -i ja_JP ja_JP.utf8
X関連の起動エラー対策

こんなのが出るので対処する。

Failed to connect to the bus: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory
 # /etc/init.d/dbus start

Cypress のインストール

依存パッケージのインストール

# sudo apt-get update
# sudo apt-get install libgtk2.0-0 libgtk-3-0 libnotify-dev libgconf-2-4 libnss3 libxss1 libasound2 libxtst6 xauth xvfb

Cypress のインストール

yarnで入れていく関係上、package.json等を更新するため、予めproject フォルダで実行する

# cd your_project_path
# yarn add -D cypress
起動オプションの追加

package.jsonに以下を追記する。jsonファイルなのと、scriptsの項はプロジェクト向けに何かしら書いてあるはずなので追記方法については適宜実施。

  "scripts": {
    "cy:open": "cypress open",
    "cy:run": "cypress run",
  },

typescript 向け設定

以下を見ながら実行する
https://docs.cypress.io/guides/tooling/typescript-support.html#Install-TypeScript

1
1
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
1
1