LoginSignup
0

More than 1 year has passed since last update.

Cypress 認証情報を保持して自動化へ Cognito編〜

Posted at

はじめに

現在、SESとして自社開発に携わっているエンジニア一年生です。e2eテストを初めて作成するにあたって、ユーザー認証(今回は、AWSCognito)を考慮することに少し手こずったので備忘録としての記事です。また、もし同じ内容につまづいた方へ参考程度になればいいなと思っております。

AWS-amplifyの利用

今回はAWSのCognitoを使用したユーザー認証を行なっているので、アクセスするために以下のaws-amplifyを使用して認証情報を取得します。

npm install --save aws-amplify

Cognitoを利用した認証自動化

Cypressでオリジナルのメソッドを生成するにあたって、Cypress.Commands.add()で新しく作成することができるので今回は使用時に、login(username,password)となるように作成していく。

AWSのCognitoを使用しているので、リージョンやプールIDなどを設定する。
そして、aws-amplify内のsignIn()を使用して認証情報を取得する。

/support/commnads.ts
import Amplify, { Auth } from 'aws-amplify';

Amplify.configure({
  Auth: {
    mandatorySignIn: true,
    region: **********,
    userPoolId: **********,
    identityPoolId: **********,
    userPoolWebClientId: **********,
  },
});

Cypress.Commands.add('login', (username, password) => {
  return Auth.signIn(username, password)
    .then((user) => {
      console.log('===> user', user);
      const session = Auth.currentSession();
      console.log('===> session', session);
    })
    .catch((err) => console.log('===> err', err));
});

そして、カスタムメソッドの型定義を入力していく。

/support/index.d.ts
/// <reference types="cypress" />

declare namespace Cypress {
  interface Chainable<Subject> {
    login(username: string, password: string): Chainable<any>;
  }
}

Cognito内で保存してあるユーザー情報を指定することで認証情報を取得することで、ログイン状態を保持してテストを走らせることができる。

/integration/ぱす
import '../support/commnads';

  it('cognito settion on', () => {
    cy.login(ユーザーID, パスワード);
    cy.visit('/');
  });

ちなみに今回のCypressについて

簡単にまとめている記事があったので以下を参考にしました。
https://blog.microcms.io/cypress-react-e2e/

参考記事

感想・まとめ

初現場で0⇨1でE2Eテストをしていく中でユーザー情報を保持するサイトが多い中こういった工夫が必要だと思いました。また、CSSフレームワークを使用しているとテストしたいタグを指定するのにデベロッパーツールで確認するとマテリアルコンポーネントだと、指定場所が変わってくるので確認に手間がかかりました。

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
0