测试方法调用 vue 测试实用程序中的 `mounted` 生命周期挂钩,现在`methods`已被弃用,并将在下一个主要版本中删除

testing method calls in `mounted` lifecycle hook in vue test utils now that `methods` is deprecated and will be removed in next major version

我的组件中有以下生命周期钩子:

  async mounted () {
    await this.fetchTabData()
  },

所述方法调用解耦方法,因为它请求的数据可以在运行时根据用户 activity 刷新(即在每个调用异步数据的“选项卡”之间切换)

为了获得上述内容的测试覆盖率,我写了以下内容:

describe('mounted', () => {
    test('test', async () => {
      const fetchTabData = jest.fn()
      wrapper = await shallowMount(Overview, {
        store: new Vuex.Store({ ... }), 
        ...
        methods: { fetchTabData }
      })

      expect(fetchTabData).toHaveBeenCalled()
    })
  })

VTU告诉我

[vue-test-utils]: overwriting methods via the methods property is deprecated and will be removed in the next major version. There is no clear migration path for the methods property - Vue does not support arbitrarily replacement of methods, nor should VTU. To stub a complex method extract it from the component and test it in isolation. Otherwise, the suggestion is to rethink those tests.

当给定的复杂方法本身是一个生命周期钩子时,因此提出的解决方案是什么(如果有one/are)?

下面通过了我的测试,警告不再出现

[编辑:澄清一下,Overview 是要测试的组件]

describe('mounted', () => {
    test('test', async () => {
      const fetchTabData = jest.fn()
      Overview.methods.fetchTabData = fetchTabData
      wrapper = await shallowMount(Overview, {
        store: new Vuex.Store({ ... }), 
        ...
      })

      expect(fetchTabData).toHaveBeenCalled()
    })
  })

理论上,同样的方法应该适用于生命周期挂钩调用方法的其他实例。