简体   繁体   English

Vue.js + Nuxt.js-在单元测试head()方法时,为什么我的计算属性未定义?

[英]Vue.js + Nuxt.js - Why is my computed property undefined when I unit test a head() method?

I have a Vue.js + Nuxt.js component with a head() method: 我有一个带有head()方法的Vue.js + Nuxt.js组件:

<script>
    export default {
        name: 'my-page',
        head() {
            return { title: `${this.currentPage}` };
        },
        ...
    }
</script>

currentPage is a computed property. currentPage是一个计算的属性。

When I run my application, the component runs correctly and it sets the page title to the right value. 当我运行我的应用程序时,该组件将正确运行,并将页面标题设置为正确的值。

When I run this code from a Jest + Vue Test Utils unit test, the code fails however: 当我从Jest + Vue Test Utils单元测试运行此代码时,该代码将失败:

it('should set the title to "my page"', () => {

    const options = {
        computed:{
            currentPage: () => {
                return 'My Title';
            }
        }
    };

    const target = shallowMount(MyPage, options);

    const actual = target.vm.$options.head();

    expect(actual.title).to.equal("My Title");

});

The test fails with the message: 测试失败,并显示以下消息:

AssertionError: expected undefined to equal 'My Title' AssertionError:期望未定义等于“我的标题”

Why is the computed property undefined even though I mock it? 为什么即使我模拟了计算属性也未定义?

Does the fact that I invoke the head() method through target.vm.$options have anything to do with it? 我通过target.vm.$options调用head()方法的事实是否与此有关?

您需要将上下文传递给您的电话。

const actual = target.vm.$options.head.call(target.vm);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM