如何通过在 beforeEach 钩子中浅层安装 vue 组件来干燥代码?

ilr*_*ock 5 javascript vue.js jestjs vue-test-utils

我第一次使用 vue-test-utils 在 Vue 应用程序中实现一堆单元测试。测试确实有效,但是,我想干燥代码。

目前我正在将以下代码添加到每个测试中:

const wrapper = shallowMount(ConceptForm, {
    localVue,
    router,
    propsData: { conceptProp: editingConcept }
});
Run Code Online (Sandbox Code Playgroud)

使测试看起来像这样

it('shows the ctas if the state is equal to editing', () => {
    const wrapper = shallowMount(ConceptForm, {
        localVue,
        router,
        propsData: { conceptProp: editingConcept }
    });

    expect(wrapper.find('#ctas').exists()).toBe(true)
});
Run Code Online (Sandbox Code Playgroud)

我这样做是因为我需要将这个特定的 propsData 传递给包装器。有什么方法可以让我在 beforeEach 中浅层安装组件,然后传递 prop 吗?

谢谢!

eta*_*han 2

setProps我认为你可以使用包装对象的功能来实现你想要的。考虑以下示例:

let wrapper;
beforeEach(() => {
    wrapper = shallowMount(ConceptForm, {
        localVue,
        router,
        propsData: { conceptProp: editingConcept }
    });
});

it('shows the ctas if the state is equal to editing', () => {
    wrapper.setProps({ conceptProp: editingConcept });
    expect(wrapper.find('#ctas').exists()).toBe(true)
});
Run Code Online (Sandbox Code Playgroud)