2

我正在使用from 的函数EditUser在测试中安装一个组件。有一个子组件。应该按原样安装所有子组件,而不是存根它们。我正在使用like this访问components方法。它在浏览器中工作正常,但在测试中被设置为空对象并且无法访问提交方法。我正在使用 jest 来测试我的组件。mountvue-test-utilsEditUserChangePasswordmountChangePasswordsubmitrefthis.$refs.changePassword.submit()$refsvue

EditUSer.vue组件中

updatePassword() {
  this.$refs.changePassword.submit()
    .then(data => {
       this.successMessage = data.message
       this.$bvModal.hide('change-password-modal')
     })
     .catch(data => {
       console.error(data.message)
      })
}

在模板中

<b-modal id="change-password-modal" title="Change Password" size="lg" @ok="updatePassword">
    <change-password ref="changePassword" :id="id"></change-password>
</b-modal>

ChangePassword.vue组件中我有一个提交方法

submit() {
  return this.form.patch('/api/users/' + this.id + '/password')
}

测试中

it ('updates password', async () => {
    moxios.stubRequest('/api/users/1/password', {
      status: 200,
      response: {
        message: 'Password updated successfully!'
      }
    })

    const wrapper = mount(EditUser, { propsData: { id: 1 } })
    const testUtils = new TestUtils(wrapper)

    wrapper.vm.updatePassword()

    await flushPromises()

    testUtils.see('Password updated successfully!')
  })

它在浏览器中运行良好,但在测试中(开玩笑)我收到了这个错误

TypeError: Cannot read property 'submit' of undefined

      262 |       },
      263 |       updatePassword() {
    > 264 |         this.$refs.changePassword.submit()
          | ^
      265 |             .then(data => {
      266 |               this.successMessage = data.message
      267 |               this.$bvModal.hide('change-password-modal')

      at VueComponent.updatePassword (src/Users/EditUser.vue:264:1)
      at Object.<anonymous> (tests/unit/users/editUser.spec.js:64:16)
4

0 回答 0