Vue测试-如何从组件内的组件访问道具?

时间:2020-10-28 14:20:14

标签: unit-testing vue.js vue-test-utils

我要测试的组件中有一个相当简单的布局,除其他模板外,我有以下布局:

...
<Skeleton :show="showSkeleton" rows="1">
    <BannerActionBar>
        <BannerActionButton :href="statementHref">
            {{ statementButton }}
        </BannerActionButton>
    </BannerActionBar>
</Skeleton>
...

这将呈现一个简单的Skeleton加载程序,该加载程序在加载数据时显示闪烁的div,然后在加载数据时显示其中的组件。 BannerActionBar本质上只是一个简单的导航栏,而BannerActionButton实际上只是一个导航项。目前只有一个。

我正在测试是否用期望值填充了BannerActionButton组件上的href属性。所以我的测试看起来像这样:

    fit("displays Statement link with correct href", async (done: Function) => {
        const apiService = new ApiService();
        const auth = new AuthService();
        const route = {
            params: {
                id: 12345
            }
        };

        const wrapper = shallowMount(WrapperPage, {
            store,
            localVue,
            mocks: {
                $api: apiService,
                $auth: auth,
                $route: route
            }
        });
        
        const summaryBannerActionButtonComponent = wrapper.findComponent(BannerActionButton);

        wrapper.vm.$nextTick(() => {
            expect(summaryBannerActionButtonComponent.isVisible()).toBeTruthy();
            expect(summaryBannerActionButtonComponent.text()).toBe("Statement");
            expect(summaryBannerActionButtonComponent.props().href).toBe(`/statement/12345`);
            done();
        });        
    });

通常,这是我尝试测试组件道具时很多测试的外观,通常情况下会很好。但是,由于summaryBannerActionButtonComponent.props()返回空对象的事实,测试失败。

最初,我认为我没有等待足够的时间,但是在包装器,我要测试的组件和父组件上尝试了许多不同的$ nextTick等待时,我很确定这不是问题。

我还尝试通过在Skeleton组件和操作栏组件上执行wrapper.findComponent()来抓取我要测试的组件,从而遍历一系列组件,但这也无济于事。

我注意到,如果我将视图代码更改为如下所示,则测试将按预期通过:

...
<Skeleton :show="showSkeleton" rows="1">
    <BannerActionButton :href="statementHref">
        {{ statementButton }}
    </BannerActionButton>
    <BannerActionBar>
    </BannerActionBar>
</Skeleton>
...

所以我怀疑这与被测组件的深度有关。我已经尝试搜索此问题,但没有找到任何帮助的方法。

我也确实认为问题可能是组件上发生的实际错误,这意味着组件道具没有正确渲染。但是,我从未在控制台中收到任何错误,并且请确保我已注释掉大多数组件代码,并且仍然遇到相同的问题。

此外,我已经在控制台上记录了statementHref属性代码,以确保道具确实被击中并且确实击中了道具(我可以在测试日志中看到控制台的输出)。

在此先感谢您提供任何帮助或提示。

0 个答案:

没有答案