使用引导vue b-form-input的vue js组件中的单元测试输入

时间:2018-09-11 13:53:28

标签: unit-testing vue.js tdd bootstrap-vue

我有一个组件,该组件利用引导Vue b-form-input,我正在尝试使用Jest对其进行单元测试:

<template>
    <div>
        <div class="cartulary" @click="click">
            <div :class="'classification ' + active">
                <fuse-icon @click="updateProduct($event, 'delete')" iconClass="dismiss" customCss="float-right"></fuse-icon>
                <div class="row align-items-center">
                    <div class="col-lg-3">
                        <div class="product-name">
                            {{ productData.name }}
                        </div>
                    </div>
                    <div class="col-lg-9">
                        <div class="row">
                            <!-- Contract ID -->
                            <div class="col-lg-4">
                                <div class="row">
                                    <div class="col-lg-5" id="contract-id-label">
                                        <span class="detail-label">
                                           Contract ID *
                                        </span>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-lg-12" id="contract-id-input">
                                        <b-form-input
                                            placeholder="7-digit code"
                                            :value="productData.contractId"
                                            @input="updateProduct($event, 'contractId')"
                                            aria-describedby="contractIdFeedback"
                                            autocomplete="off"
                                            maxlength="7"
                                            :state="this.productValidationStates.contractId"
                                            @keydown.native="isNumericAllowed($event)"
                                        >
                                        </b-form-input>
                                        <b-form-invalid-feedback id="contractIdFeedback">
                                           7 digits required
                                        </b-form-invalid-feedback>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    import validationHelpers from '../../../helpers/validationHelpers'
    export default {
        name: 'EnercareLineItem',
        props: [
            'options',
            'active'
        ],
        data() {
            return {
                datePickerOptions: {
                    type: 'datetime',
                    format: 'MM/dd/yyyy hh:mm A',
                    placeholder: 'Select date and time'
                },
                productData : this.options,
                productValidationStates: {
                    contractId: '',
                    caseId: ''
                },
                isValid: false
            }
        },
        methods: {
            click() {
                this.$emit('click')
            },
            /**
             * Only allow the user to enter numbers, otherwise prevent the
             * input from registering
             */
            isNumericAllowed(event) {
                if (!validationHelpers.allowNumeric(event)) {
                    event.preventDefault()
                }
            },
            /**
             * updateProducts() sends the product data up to the parent.
             */
            updateProduct(value, type) {
                if (type === 'delete') {
                    this.$emit('delete')
                    return
                }
                this.productData[type] =  value
                console.log('#################################')
                console.log('Here in updateProduct()')
                console.log('#################################')
                this.setValidationStates()
                this.$emit('update', {
                    encrProductData: this.productData,
                    isValid: !Object.values(this.productValidationStates).includes('invalid')
                })
            },
            setValidationStates() {
                console.log('#################################')
                console.log('Here in setValidationStates()')
                console.log(this.productData.contractId)
                console.log('#################################')
                this.productValidationStates.contractId = this.productData.contractId.length !== 7 ?  'invalid' : 'valid'
                switch (this.productData.caseId.length) {
                    case 0:
                        this.productValidationStates.caseId = 'reset'
                        break
                    case 8:
                        this.productValidationStates.caseId = 'valid'
                        break
                    default:
                        this.productValidationStates.caseId = 'invalid'
                        break
                }
            }
        },
        created() {
            this.setValidationStates()
        },
        updated() {
            console.log('I just updated', this.options)
        }
    }
</script>

在单元测试中,我试图在b-form-input上设置值并触发input和/或change事件,以便组件中的this.productData.contractId数据更新:

import Vuex from 'vuex'
import BootstrapVue from 'bootstrap-vue'
import { shallowMount, createLocalVue } from '@vue/test-utils'
import EnercareLineItem from '../../resources/assets/js/components/formfields/enercare/EnercareLineItem'
import BaseField from '../../resources/assets/js/components/BaseField'
​
const Vue = createLocalVue()
Vue.use(Vuex)
Vue.use(BootstrapVue)
​
describe('EnercareLineItem', () => {
  describe('Contract Id input', () => {
    it('is valid at a length of 7', () => {
      let options = {
        index: 0,
        name: 'Hot Water Heater Tune Up',
        contractId: '',
        appointmentTime: '2018-01-01T12:00:00Z',
        caseId: ''
      }
​
      const wrapper = shallowMount(EnercareLineItem, {
        propsData: { options }
      })
​
      const contractIdInput = wrapper.find('#contract-id-input > b-form-input')
      expect(contractIdInput.attributes().state).toBe('invalid')
      contractIdInput.element.value = '1234567'
      contractIdInput.trigger('input')
      expect(contractIdInput.attributes().state).toBe('valid')
    })
  })
})

使用contractIdInput.trigger('input') does run the updateProduct($ event,'contractId')method, evidenced by the console.log in the updateProduct method. It then goes into the setValidationStates()method. Once there, the console.log(this .productData.contractId)produces different results between running the unit test and running it in the browser. In the unit test, the value returned from the console.log is事件{isTrusted:[Getter]} . When I run the same code in Chrome, the initial console.log is an empty string. Then when I add values to the b-form-input field, the console .log`注销我输入该字段的值。

我的第一个问题是我需要做些什么来更新b-form-input字段中的输入,以使我的测试接收正确的值?

我的第二个(也是不太重要的问题)是为什么我在运行单元测试时得到Event { isTrusted: [Getter] } console.log的原因?

0 个答案:

没有答案