Karma / Jasmine / Vue / Sinon单元测试 - 模拟一个Vue子组件?

时间:2017-06-16 14:53:34

标签: vue.js karma-runner karma-jasmine vuejs2 sinon

我想独立于其子组件测试我的父组件:

Parent.vue

$('#buttonID').click(function() {
  var limit = $('#inputID').val();
  $('div#divID').html("<?php echo $fib->getFibonacci( " +limit+");?>");
});

Child.vue

<template><div>
    Hello World
    <child></child>
</div></template>

<script>
    import Child from './Child.vue'

    export default {
        components: {Child}
    }
</script>

parent.spec.js

<template><div>Child</div></template>

<script>
    export default {}
</script>

结果失败

import Vue from 'vue'
import Parent from '../components/Parent.vue'

describe('Parent', () => {

    it('should show mocked child', function () {
        const Child = {
            template: '<div>Mocked</div>'
        }

        const vm = new Vue({
            template: '<parent></parent>',
            components: {Parent, Child},
        }).$mount();

        expect(vm.$el.textContent).not.toContain('Child')
        expect(vm.$el.textContent).toContain('Mocked')
    });
});

1 个答案:

答案 0 :(得分:1)

使用浅渲染来独立测试Vue组件。

有几个Vue帮助程序库具有浅层渲染 - 这里是ctx.statehttps://github.com/wrseward/vue-unit#shallow)的示例:

vue-init

如果你需要能够像我原来的问题一样用模拟替换组件,请参阅vuenit library's stubComponents method,我也能够开始工作 - 关键线是import { mount, shallow, beforeEachHooks, afterEachHooks } from 'vue-unit' import Parent from '../components/Parent.vue' describe('Parent', () => { beforeEach(beforeEachHooks) it('should show mocked child', function () { const vm = shallow(Parent) expect(vm.$el.textContent).toContain('Hello World') expect(vm.$el.textContent).not.toContain('Child') }); afterEach(afterEachHooks) });

有趣的是,Vue.js unit testing documentation声称有一天他们可能会将这样的测试助手添加到核心:

  

我们计划开发一组常见的测试助手,这样可以更简单地渲染具有不同约束的组件(例如,忽略子组件的浅层渲染)并断言它们的输出。

相关问题