【问题标题】:How to unit test a 'v-show' property of a Vue Component如何对 Vue 组件的“v-show”属性进行单元测试
【发布时间】:2017-07-20 20:25:30
【问题描述】:

当您有一个基于模型显示的按钮时,如下所示:

<button v-show="title != ''">Add it</button>

你会如何测试这个?我一辈子都想不通。

我尝试了以下方法(使用 Jest,但运行器/框架无关紧要):

describe('btn test', () => {
    it('should hide the add button initially', () => {

        // vm is set up here to be the vue component

        expect(vm.$el.querySelector('button').style.display).toBe('none') // works

        // Update the input field (which has v-model="title")
        vm.$el.querySelectorAll('input').value = 'fd'

        expect(vm.$el.querySelector('button').style.display).toBe('block') // is still 'none'

        // Update directly through vm prop
        vm.title = 'sheep'

        Vue.nextTick(() => {
            expect(vm.$el.querySelector('button').style.display).toBe('block') // is still 'none'
        })

    })
})

【问题讨论】:

    标签: javascript unit-testing testing vue.js jestjs


    【解决方案1】:

    通过 DOM API 更改输入的值将不会通过 v-model 更新数据,因为它不会触发 v-model 侦听的输入事件。

    所以没有数据改变,因此,v-show 仍然是true

    解决办法,修改虚拟机上的数据。

    vm.title = 'fd'
    

    并像上一行一样使用 $nextTick,因为只有这样更新才会在 DOM 中

    【讨论】:

    • 但是我在上面的示例中这样做了(第 14 行),但这并不能解决问题
    【解决方案2】:

    我偶然发现了它。原来测试需要一个 done 参数。

    这不起作用(注意 done 参数和回调)

    it('should hide aap', () => {
        expect(vm.$el.querySelector('.aap').style.display).toBe('none')
        vm.showAap = true
        Vue.nextTick(() => {
            // vm.showAap = false again
            expect(vm.$el.querySelector('.aap').style.display).toBe('')
        })
    })
    

    这确实有效:

    it('should hide aap', (done) => {
        expect(vm.$el.querySelector('.aap').style.display).toBe('none')
        vm.showAap = true
        Vue.nextTick(() => {
            expect(vm.$el.querySelector('.aap').style.display).toBe('')
            done()
        })
    })
    

    【讨论】:

    • 除了nextTick 魔术之外,您还可以简单地完成:vm.setData({ showApp: true });。这可以解决所有问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2019-12-05
    • 2021-04-29
    • 2020-04-02
    • 1970-01-01
    相关资源
    最近更新 更多