Vue.js 用 Jest 进行测试,类绑定(bind)失败

标签 vue.js testing jestjs frontend vue-component

我正在尝试测试一个组件,该组件应该在用户单击时隐藏。功能在浏览器中工作,但在使用 Jest 进行自动化测试时测试失败。

这是测试:

 it(`If the local variable is set to be clicked, 
     then the tip is hidden`, () => {
    const wrapper = mount(Component, { props });
    wrapper.setData({ was_clicked: true });
    wrapper.vm.$forceUpdate();
    expect(wrapper.classes()).toContain("hide"); // fails here
    expect(wrapper.find(".toast").isVisible()).toBe(false);
});

这是组件:

<template>
    <div @click="hide" class="toast" :class="{ hide: was_clicked }">
        ...
    </div>
</template>
<script>
export default {
    name: ...,
    data() {
        return {
            was_clicked: false,
        };
    },
    props: {
        ...
    },
    methods: {
        hide(event) {
            this.was_clicked = true;
        },
    },
};
</script>

我试图在测试中添加和删除 wrapper.vm.$forceUpdate();,此外,我还测试了 wrapper.vm 的 nextTick

最佳答案

wrapper.vm.$forceUpdate(); 返回一个 promise 。您应该 await 该 promise (并将该函数标记为 async),或者将其后面的 expect() 移至 .然后。同样的情况也适用于 vm.$nextTick();。这是与我一起工作的代码:

it(`If the local variable is set to be clicked, then the tip is hidden`, async () => {
    const wrapper = mount(Tip, { props });
    wrapper.setData({ was_clicked: true });
    await wrapper.vm.$nextTick();
    expect(wrapper.classes()).toContain("hide");
    expect(wrapper.isVisible()).toBe(false);
});

关于Vue.js 用 Jest 进行测试,类绑定(bind)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61608804/

相关文章:

typescript - 使用 Jest 测试 i18next 时如何修复 `TypeError: Cannot read property ' 类型'未定义`

javascript - 是否可以将 Angular JS 用于 JAMstack 架构?

javascript - 如何更改Vue上Props的名称?

javascript - 使用 onBlur 触发器时如何清除模糊验证错误?

javascript - 在 v-for 循环的某个索引上添加一个空 div

ruby-on-rails - Rails 测试未加载自定义应用程序配置文件

angularjs - 在项目的构建或源版本上运行 AngularJS/Jasmine 测试

testing - Jenkins 多配置项目处理并发设备使用

javascript - Jest 手动模拟未返回正确的值

javascript - 我如何使用 jest 在 vuejs 中测试计算属性?