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

uri*_*rig 4 javascript unit-testing vue.js nuxt.js

我有一个 Vue.js + Nuxt.js 组件,其head()方法如下:

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

currentPage是一个计算属性。

当我运行我的应用程序时,该组件正确运行并将页面标题设置为正确的值。

当我从 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");

});
Run Code Online (Sandbox Code Playgroud)

测试失败并显示以下消息:

断言错误:预期未定义等于“我的标题”

为什么计算属性未定义,即使我模拟它?

head()我通过调用该方法的事实target.vm.$options与它有什么关系吗?

Ald*_*und 6

您需要将上下文传递到 head 调用中。

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