2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Cypressで躓いた所 クロスドメイン・iframe

Last updated at Posted at 2021-04-28

はじめに

E2Eテスト自動化でCypressを使った際に躓いてこう解決したを備忘録として残しておく。

Cypressとは

ここを参照。
Cypressを使ってみるにはここ。

クロスドメイン

E2Eテスト自動化で躓くポイントの1つであるクロスドメインの部分でやはり躓いた。

躓きポイント

Cookieを用いて認証情報をやり取りしていたが、それが引き継がれない事でデータが取得できなかったり、画面が描画されなかったりという事が起きた。

原因

Cypressでは、デフォルトで新しいテストが開始される前にすべてのCookieが自動的にクリアされる仕様になっているため。

解決策

beforeでログイン処理を行い、そこで取得したCookieをbeforeEachにてCypress.Cookies.preserveOnceで設定する。
※システムによってはCypress.Cookies.preserveOnceではうまくいかず、Cypress.Cookies.defaultも併用するとうまくいく事もある。

cookie.js
  before('ログインする', () => {
    // カスタムコマンド
    cy.login('id', 'password')
  })

  beforeEach('Cookiesの設定', () => {
    const cookies = Cypress.env('COOKIES')
    
    cookies.forEach(cookie => {
      Cypress.Cookies.preserveOnce(cookie.name)

      // preserveOnceでうまくいかない時はこっちも併記するとうまくいく場合もある
      // Cypress.Cookies.default({ preserve: `${cookie.name]`})
    })
  })

  it('do something', () => {
  })

  it('check something', () => {
  })
command.js
Cypress.Commands.add('login', (id, password) => {
  // Cookiesの初期化
  cy.clearCookies();

  cy.visit('/login');
  cy.get('#id').type(id);
  cy.get('#password').type(password);

  // ログイン後にCookiesを取得し、それをCypressの環境変数'COOKIES'に設定
  cy.Cookies().then(cookies => {
    Cypress.env('COOKIES', cookies);
  });
})

参考文献

iframeが使われているWebサイトの操作

躓きポイント

iframeを使っている場合、通常の実装方法では要素を捕捉できずtypeclickができなかった。

解決策

iframe-test.js
cy.get('#iframe') // ←ここはiframeのDOMを指定するセレクタであればOK
  .its('0.contentDocument').should('exist')
  .its('body').should('not.be.undefined')
  .then(cy.wrap)
  .as('iframe')

cy.get('@iframe')
  .find('#name')
  .type('hogehoge')

cy.get('@iframe')
  .find('#submit')
  .click()

参考文献

関連記事

2
0
1

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?