
Amplify ConsoleでCypressによるE2Eテストが実行できるようになりました!Vueアプリで試してみた #Amplify #Vue.js #Cypress
この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Amplify ConsoleがCypressのテストをサポート!
Amplify ConsoleでE2Eテスティングフレームワーク「Cypress」がサポートされました!
CypressはWebアプリ開発のお供として、現在非常によく使われているテスティングフレームワークかと思います。Amplify Consoleでサポートされたことによって、E2Eテストを含めたCI/CD環境がサクッと構築できるようになりました。
早速使ってみました!Cypressを使ってログイン操作のE2Eを試してみます。
試すためのWebアプリを用意する
Amplify自体の説明は省きます。まずは以下のコマンドでVueアプリを作ります。
$ vue create amplify-vue-cypress $ cd amplify-vue-cypress
次にVueアプリにAmplifyをインストールします。
$ yarn add aws-amplify aws-amplify-vue
次にAmplify CLIを使って、Auth機能を追加します(Cognito User Poolsを構築)。
$ yarn global add @aws-amplify/cli $ amplify init $ amplify add auth $ amplify push
main.js でAmplify Pluginを使うように設定します。
import Vue from 'vue'
import App from './App.vue'
import Amplify, * as AmplifyModules from 'aws-amplify'
import { AmplifyPlugin } from 'aws-amplify-vue'
import awsconfig from './aws-exports'
Amplify.configure(awsconfig)
Vue.config.productionTip = false
Vue.use(AmplifyPlugin, AmplifyModules)
new Vue({
  render: h => h(App)
}).$mount('#app')
App.vue を以下のように書き換え、ログイン画面およびログイン後の画面を表示できるようにします。
<template>
  <div id="app">
    <div v-if="!signedIn">
      <amplify-authenticator></amplify-authenticator>
    </div>
    <div v-if="signedIn">
      <h3>Signed in!</h3>
      <amplify-sign-out></amplify-sign-out>
    </div>
  </div>
</template>
<script>
import { Auth } from 'aws-amplify'
import { AmplifyEventBus } from 'aws-amplify-vue'
export default {
  name: 'app',
  data () {
    return {
      signedIn: false
  },
  async beforeCreate() {
    try {
      await Auth.currentAuthenticatedUser()
      this.signedIn = true
    } catch {
      this.signedIn = false
    }
    AmplifyEventBus.$on('authState', info => {
      this.signedIn = info === 'signedIn'
    }); 
  }
}
</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
ローカルで起動してみましょう。
$ yarn serve
以下のようなログイン画面が立ち上がり、実際にサインアップ・サインインができるようになります。
Cypressの導入
次にCypressをインストールします。
$ yarn add --dev cypress $ yarn cypress open
以下の画面が表示されればインストール成功です。
次にログインできることをテストする、新しいSpecを作ります。
describe('Authenticator:', function() {
  // Step 1: setup the application state
  beforeEach(function() {
    cy.visit('/');
  });
  
  describe('Sign In:', () => {
    it('allows a user to signin', () => {
      // Step 2: Take an action (Sign in)
      cy.get(selectors.usernameInput).type("DUMMY_USERNAME");
      cy.get(selectors.signInPasswordInput).type("DUMMY_PASSWORD");
      cy.get(selectors.signInSignInButton).contains('Sign In').click();
      // Step 3: Make an assertion (Check for sign-out text)
        cy.get(selectors.signOutButton).contains('Sign Out');
    });
  });
});
export const selectors = {
  // Auth component classes
  usernameInput: '[data-test="username-input"]',
  signInPasswordInput: '[data-test="sign-in-password-input"]',
  signInSignInButton: '[data-test="sign-in-sign-in-button"]',
  signOutButton: '[data-test="sign-out-button"]'
}
次に cypress.json にローカルで起動するURLを設定します。
{ 
  "baseUrl": "http://localhost:8080/"
}
再度 yarn cypress open でCypressを開き、テストを実行してみます。以下のようになればテスト成功です。
Amplify ConsoleでCI/CDする
総仕上げです!
上記のVueプロジェクトをGitHubなどのGitリポジトリ上にプッシュした上で、AWS Management ConsoleのAmplify Consoleを開きます。
新規プロジェクトを作成します。今回はGitHubを選択。
対象のリポジトリ、ブランチを選択します。
アプリ設定です。「Auto-detected framework settings」の「Testing framework」に「Cypress」と表示されていることが確認できます。 つまりAmplify Consoleがソースコードを読み取り、いい感じに自動設定してくれているということです。相変わらず超絶便利です。
なお、Build settingsは以下のように設定されます。Vue CLIで作成している場合は起動コマンドが npm serve になるため、変更が必要です。
version: 0.1
backend:
  phases:
    build:
      commands:
        - '# Execute Amplify CLI with the helper script'
        - amplifyPush --simple
frontend:
  phases:
    preBuild:
      commands:
        - yarn install
    build:
      commands:
        - yarn run build
  artifacts:
    baseDirectory: dist
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
test:
  artifacts:
    baseDirectory: cypress
    configFilePath: '**/mochawesome.json'
    files:
      - '**/*.png'
      - '**/*.mp4'
  phases:
    preTest:
      commands:
        - npm install
        - npm install wait-on
        - npm install  mocha@5.2.0 mochawesome mochawesome-merge mochawesome-report-generator
        - 'npm serve & npx wait-on http://localhost:8080'
    test:
      commands:
        - 'npx cypress run --reporter mochawesome --reporter-options "reportDir=cypress/report/mochawesome-report,overwrite=false,html=false,json=true,timestamp=mmddyyyy_HHMMss"'
    postTest:
      commands:
        - npx mochawesome-merge --reportDir cypress/report/mochawesome-report > cypress/report/mochawesome.json
作成を完了すると、数分後にCI/CDが完了します。ビルド結果を確認すると、新たに 「Test」 タブが追加されています。**
テストの動画(mp4ファイル)がダウンロードでき、実際のE2Eテストの様子が動画で確認できます。
以降はリポジトリにPushするだけで、自動実行されます。
E2Eテスト環境までもサクサク作れるように!
Amplify ConsoleとCypressが組み合わさることによって、かなり強力になりました。
WebアプリのホスティングからE2Eテストまでの環境が秒で構築できます。 ぜひお試しください!






















