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(...)
みたいな感じでメソッドチェーンで書けるのでとても便利ですねー