如何在异步方法中测试Vue组件方法调用

ubbxdtey  于 2023-06-24  发布在  Vue.js
关注(0)|答案(2)|浏览(178)

我想我是在努力地嘲笑我的方法。下面是我的情况,我有一个组件有两个方法;

name: 'MyComponent',
    methods: {
       async submitAction(input) {
           // does await things
           // then ...
           this.showToastMessage();
       },
       showToastMessage() {
           // does toast message things
       },
    }

我想写一个测试,当submitAction(input)被调用时,它将AssertshowToastMessage()被调用。我的基本测试是这样的

test('the toast alert method is called', () => {
      let showToastMessage = jest.fn();
      const spy = jest.spyOn(MyComponent.methods, 'showToastMessage');
      const wrapper = shallowMount(MyComponent, { localVue });

      const input = // some input data
      wrapper.vm.submitAction(input); // <--- this calls showToastMessage
      expect(spy).toHaveBeenCalled();
    };

注意:localVue在文件const localVue = createLocalVue();的顶部声明
我确认了在测试过程中submitAction()showToastMessage()方法都被调用了,方法是偷偷使用console.log()并在测试输出中观察它,但是测试仍然失败;

expect(jest.fn()).toHaveBeenCalledWith(...expected)

    Expected: called with 0 arguments

    Number of calls: 0

      566 |           const wrapper = shallowMount(MyComponent, { localVue } );
      567 |           wrapper.vm.submitAction(input);
    > 568 |           expect(spy).toHaveBeenCalledWith();

两种方法我都试过了

const parentSpy = jest.spyOn(MyComponent.methods, 'submitAction');
    const spy = jest.spyOn(MyComponent.methods, 'showToastMessage');
    // ...
    expect(spy).toHaveBeenCalled()

结果相同,测试失败。
我错过了什么?
技术堆栈:vue 2、jest、node 14

gab6jxml

gab6jxml1#

@TekkSparrow,你可以将一堆东西传入shallowMount函数。它接受一个对象作为第二个参数,该参数可以类似于

import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'

const localVue = createLocalVue()
localVue.use(Vuex)

let mocks = {
  // this could be something like the below examples
  // I had in a previous project
  $route: {
    query: '',
    path: '/some-path'
  },
  $router: [],
  $validator: {
    validateAll: jest.fn()
  },
  $toast: {
    show: jest.fn(),
    error: jest.fn()
  },
}
let propsData = {
  // some props you want to overwrite or test.
  // needs to be called propsData
}
let methods = {
  showToastMessage: jest.fn()
}
let store = new Vuex.Store({
  actions: {
    UPLOAD_ASSET: jest.fn(),
  },
})

const wrapper = shallowMount(MyComponent, { mocks, propsData, methods, store, localVue })

我相信通过执行类似于上面的操作,您的模拟函数将运行并被Jest间谍记录。

yfjy0ee7

yfjy0ee72#

我花了一分钟来实现/尝试这个,但看起来因为我的调用函数是异步的,所以我应该让我的测试异步,并等待主方法调用。这似乎已经成功了。以下是我的解决方案:

test('the toast alert method is called', async () => {
      let showToastMessage = jest.fn();
      const spy = jest.spyOn(MyComponent.methods, 'showToastMessage');
      const wrapper = shallowMount(MyComponent, { localVue });

      const input = // some input data
      await wrapper.vm.submitAction(input);
      expect(spy).toHaveBeenCalled();
    };

相关问题