Typescript 如何在Jest单元测试中模拟在`created`Vue lifecycle hook中调用的方法,而不在`shallowMount`中使用不推荐的`methods`参数?

Typescript 如何在Jest单元测试中模拟在`created`Vue lifecycle hook中调用的方法,而不在`shallowMount`中使用不推荐的`methods`参数?,typescript,vue.js,jestjs,vue-test-utils,Typescript,Vue.js,Jestjs,Vue Test Utils,注意:链接的“重复”问题和答案没有回答我的问题,请投票重新打开,或者在评论中解释为什么关闭该问题 我有一个created()钩子,它调用doSomething()方法。我可以通过将方法参数传递到shallowMount()并使用jest.fn()覆盖来通过测试 然而,当我采用这种方法时,我会收到有关方法的弃用警告: console.error [vue-test-utils]: overwriting methods via the `methods` property is deprecate

注意:链接的“重复”问题和答案没有回答我的问题,请投票重新打开,或者在评论中解释为什么关闭该问题

我有一个
created()
钩子,它调用
doSomething()
方法。我可以通过将
方法
参数传递到
shallowMount()
并使用
jest.fn()覆盖来通过测试

然而,当我采用这种方法时,我会收到有关
方法的弃用警告:

console.error
[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.
TestComponent.Vue:

...

created() {
    doSomething();
}

...

methods: {
    doSomething(): void { /* do something */ }
}
TestComponent.test.ts:

// mounting method used for tests
function genMount() {
    const doSomething = jest.fn();
    const el = document.createElement('div');
    document.body.appendChild(el);

    return shallowMount(TestComponent, {
        localVue,
        methods: { doSomething },  // deprecated param
        store,
        mocks,
        attachTo: el,
        stubs
    });
}
如何模拟
created()
钩子中调用的方法,而不将
方法
传递到
shallowMount()
以解决弃用警告

或者,是否有办法模拟或绕过
created()
生命周期挂钩


根据警告建议,我意识到我可以导入该方法并模拟它进行测试,但我正在寻找一种替代方法,特别是在这种情况下,这样做可能会有点过头。

哇,我甚至不知道这是不推荐的。这也是我在
mounted
期间测试方法的方法,下面是我的发现。就我个人而言,我会同意第一种选择

如果您愿意改变测试理念而不是编码风格:

我想解决办法不是测试这些方法是否被调用,而是测试它们的效果是否被应用。这一切都很好,除非您处理DOM(在某些情况下,Jest/JSDOM严重缺乏功能)

否则,如果您愿意改变您的编码风格,但不想改变您的测试理念:

一个立即想到的解决方法(可能不理想)是将该方法放在另一个文件中并导入它。然后可以使用
jest.mock

其他人建议消除错误:

import { config } from '@vue/test-utils';

config.showDeprecationWarnings = false;
…但我认为这可能会造成比它所能解决的问题更多的问题。如果不是现在,那以后再说。除非您的项目决定永远不更新到更新的Vue版本,我想


这些是我能找到的唯一解决办法。我希望我能找到一个更好的答案。如果我们能在
创建的
装载的
之间停顿一下,模拟一个方法,那就太好了,但我甚至不确定该方法对象是否存在,我不知道如何找到它。

链接的“复制”并不能回答我的问题。不知道为什么会关闭。