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

Karma/Jasmine/Vue/Sinon unit tests - mock a Vue child component?

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

Parent.vue

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

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

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

Child.vue

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

<script>
    export default {}
</script>

parent.spec.js

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')
    });
});

失败结果

PhantomJS 2.1.1 (Mac OS X 0.0.0) Parent should show mocked child FAILED
    Expected '
        Hello World
        Child' not to contain 'Child'.
    webpack:///resources/assets/js/tests/parent.spec.js:16:49 <- tests/parent.spec.js:9880:49
    Expected '
        Hello World
        Child' to contain 'Mocked'.
    webpack:///resources/assets/js/tests/parent.spec.js:17:45 <- tests/parent.spec.js:9881:45

使用浅层渲染独立测试一个Vue组件

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

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)
});

如果您需要能够像我原来的问题那样用模拟实际替换组件,请参阅 vuenit library's stubComponents method,我也能够开始工作——关键线是 const vm = mount(Parent, {stubComponents: '<div>Mocked</div>'}).

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

We are planning to work on a collection of common test helpers that makes it even simpler to render components with different constraints (e.g. shallow rendering that ignores child components) and assert their output.`