LoginSignup
0
1

More than 5 years have passed since last update.

Storybook 環境での Cypress の使い方

Posted at

Storybook 環境だと、たぶんcy.get(...)とかでセレクタを取得しようとしても見つからないと思います

例えば Cypress を使って、以下の v-chip 要素の name という中身が正しいかアサーションしたいとき

<v-chip
  class="white--text font-weight-bold"
  disabled
  color="light-green"
  data-test="name"
  >{{ name }}</v-chip
>

Storybook を使っていなければ、Cypress から以下のようにして普通に取ることができる

cy.get('[data-test="name"]').should('have.text', 'サンプル')

しかし、Storybook 環境だと[data-test="name"]が見つからず、以下のようなエラーになるはず

CypressError: Timed out retrying: Expected to find element: '[data-test="name"]', but never found it.

こちらのコードのように iframe を取ってきてから、対象のセレクタを find する 関数を用意すれば HTML 要素の中身が取得できる

cy.get('#storybook-preview-iframe').then($iframe => {
  const doc = $iframe.contents()
  iget(doc, '[data-test="name"]').should('have.text', 'サンプル')
})

function iget(doc, selector) {
  return cy.wrap(doc.find(selector))
}

上記で問題は解決はしているのだが、、
でももうちょっと汎用的に使えるようにするのであれば、以下の方法が良いのではないかなと思います

cypress/support/commands.js
Cypress.Commands.add('iget', selector =>
  cy
    .get('#storybook-preview-iframe')
    .then(iframe => cy.wrap(iframe.contents().find(selector)))
)
cy.iget('[data-test="name"]').should('have.text', 'サンプル')

Cypress にはカスタムで関数を作れたり、既存の関数をオーバーライドすることが簡単にできる機能が用意されています
https://docs.cypress.io/api/cypress-api/custom-commands.html

また、カスタムで作成した関数の中で Cypress オブジェクト(型が Cypress.Chainable のもの)を return するように作っておけば、cy.iget(...).should(...)みたいな感じでメソッドチェーンで書けるのでとても便利ですねー

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