LoginSignup
1
0

More than 3 years have passed since last update.

Cypressでフォーム入力前後の要素の有無をチェックしたい

Last updated at Posted at 2021-03-30

Vueをつかったアプリを開発しているときにページ内要素をリアクティブに切り替える実装をよく目にします。
たとえば問い合わせフォームで、送信後に「ありがとうございました」という文面を表示させようとしたけど、v-elseの外に出てしまって送信前の画面に表示されちゃった! というミスは、cypressに助けてもらいたいですね。

ContactForm.vue
<template>
  <div class="contact-form">
    <h1>お問い合わせ</h1>
    <div v-if='!sent'>
      <input type='text' class='user-name' v-model='userName'>
      <input type='email' class='user-email' v-model='userEmail'>
      <button @click='sent = true' :disabled='!isValidForm'>送信する</button>
    </div>
    <div v-else>
      <p>{{userName}}</p>
      <p>{{userEmail}}</p>
    </div>
    <p>ありがとうございました</p>
    <!-- ↑ v-elseの外に出てしまった。うっかりミス!! -->
  </div>
</template>

<script>
export default {
  name: 'ContactForm',
  data() {
    return {
      userName: '',
      userEmail: '',
      sent: false
    }
  },
  computed: {
     isValidForm: function() {
      return this.userName.length> 0 && this.userEmail.length> 0
    }
  }
}
</script>

送信前の状態と、送信後の状態をテストで記述しておけば、cypressさんがきっちり叱ってくれました!

contact_spec.js
describe('お問い合わせフォーム Test', () => {
  it('問い合わせを送信できる', () => {
    cy.visit('http://localhost:8080')
    cy.contains('お問い合わせ')

    cy.contains('送信する').should('be.disabled')
    cy.contains('ありがとうございました').should('not.exist')

    cy.get('.user-name')
      .type('歳府れす')
      .should('have.value', '歳府れす')

    cy.get('.user-email')
      .type('fake@email.com')
      .should('have.value', 'fake@email.com')

    cy.contains('送信する').click()
    cy.contains('ありがとうございました')
    cy.contains('送信する').should('not.exist');
  })
})

image.png

ケアレスミスはいくら注意していても起こるときは起こる(特に起こしやすい人w)
なので、こういった仕組みでカバーできるようにしておくとケアレスミスが多い日も安心ですね!

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