LoginSignup
5
5

More than 5 years have passed since last update.

E2Eテストで会員登録などのメール認証を簡単にする方法を編み出した話

Last updated at Posted at 2018-02-07

初めに

会員登録などで一度メールを受信してメールに記載のURLをクリックすることで認証する仕組みが
よくあると思います。
seleniumなどでE2Eテストを作ったりするときにgmailを利用してメールから認証URL押して・・って
せっかく作ってもgmail側のUIが変わったすると突然テストが動かなくなったりしちゃいます。

なので、Google Apps Script(GAS)を使って自動化してみました。
https://developers.google.com/apps-script/

Google Apps Scriptに作ったスクリプト

作ったGASを外部から叩くと、HTMLを返してJavaScriptでメールにあるURLへ
リダイレクトするように作りました。

image.png

外部からGASを叩く方法は以下を参考にさせていただきました。

参考:GASのExecution APIを使ってGASを外部からぶっ叩く
https://qiita.com/soundTricker/items/1bcfc5c9e80d29a7ae4b

コード.gs
var SEARCH_TERM = 'subject:(会員仮登録のお知らせ) ';

function doGet(){
  var text = getActivateUrl();
  // HTMLテンプレート読み込み
  var template = HtmlService.createTemplateFromFile('index');
  template.foo = text;
  template.bar = text;
  return template.evaluate();
}

function getActivateUrl(){
 
  var myThreads = GmailApp.search(SEARCH_TERM, 0, 30); 
  var myMessages = GmailApp.getMessagesForThreads(myThreads); 
  
  //最新の仮登録メールを探す
  var lastNum = myMessages[0].length - 1;
  var body = myMessages[0][lastNum].getBody();
  
  // メールbodyからURLを正規表現で引っこ抜く
  // 正規表現はサイトの仕様に合わせて変更してください
  var result = body.match(/http:.*hogehoge/);

  return result;
}
index.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script language="JavaScript" type="text/javascript">
    function AutoJump() {
      window.top.location.href="<?= bar ?>";
    }
    AutoJump() ;
    </script>
  </head>
  <body onLoad="javascript:setTimeout('AutoJump()',3000);">
    <a href="<?= foo ?>">link</a>
    aaaa
  </body>
</html>

Nightwatch.jsでE2Eテストを書く

こんな感じで。

module.exports = {
    'メール登録' : function (client) {
        client
           // メール登録フォームがあるURLを開く
            .url('https://hogehoge/')
            .waitForElementVisible('body', 1000)
             // メアドを入れて送信
            .setValue('#mail', 'GASを作ったgmailアカウントのメアド')
            .click('#submit')
           // gmailが受信されるまで5秒くらい待つ
            .pause(5000)
            .end();
    },
    'GASに作ったURLを叩いてその先に進む': function(client) {
        client
           // GASで払い出されたURLに遷移→メール記載のURLにリダイレクトされる
            .url('https://script.google.com/macros/hogehoge・・・・')
           ・・・
5
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
5
5