【问题标题】:Vue Composition API + JestVue 组合 API + Jest
【发布时间】:2021-02-08 20:31:47
【问题描述】:

我正在试用 Vue3 组合 API,但在为它编写测试时遇到了一些问题。

我使用组合 API 在我的应用程序中编写了新组件(MyComponent)。 MyComponent 使用另一个使用 Options api (MyOtherComponent) 编写的组件。 如果我运行该应用程序一切正常,但是当我编写单元测试(使用 Jest)时,我开始遇到“this”不再被识别并评估为未定义的问题。

请看下面的代码sn-ps(把它当作伪代码)...

有人知道我可以如何解决或解决这个问题吗?

MyOtherComponent.vue

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template>
  <div></div>
<template>

<script lang="ts">

export default class MyOtherComponent extends Vue {
  public doSomething() {
    this.$log('MyOtherComponent is doing something!');
  }
}

</script>

MyComponent.vue

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div @click="onClick">
    <my-other-component ref="myOtherComponent" />
  </div>
</template>

<script lang="ts">
export default {
  name: 'MyComponent',
  components: ['MyOtherComponent'],
  setup() {
    const myOtherComponent = ref<MyOtherComponent | null>(null);
    const state = ref<Boolean>(false);
    
    function onClick() {
      myOtherComponent.value.doSomething().then(() => {
        state.value = true;
      });
    }
    
    return {
      onClick
    }
  }
}
</script>

MyComponent.test.ts

fdescribe('Testing MyComponent', () => {
  let wrapper: Wrapper<MyComponent>;
  
  beforeEach(() => {
    const localVue = createLocalVue();
    
    localVue.use(VueCompositionApi);
    wrapper = mount(MyComponent, { localVue };
  })

  afterEach(() => {
        wrapper.destroy();
    });

  test('post click test', async() => {
        expect(wrapper.vm.$data.state).toBeFalsy();
        await wrapper.find('div:first-child').trigger('click');
        expect(wrapper.vm.$data.state).toBeTruthy();
    });
})

【问题讨论】:

    标签: vue.js jestjs vuejs3 vue-composition-api


    【解决方案1】:

    在 Vue 3 中没有全局 Vue 实例,因此不需要createLocalVue

    你的beforeEach 会改变:

    import { mount } from '@vue/test-utils';
    
    // …
    
    beforeEach(() => {
        wrapper = mount(MyComponent);
    });
    
    // …
    

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 2018-07-29
      • 2018-07-16
      • 2021-03-08
      • 1970-01-01
      • 2022-07-19
      相关资源
      最近更新 更多