如何在Jest单元测试中模拟在“ created” Vue生命周期挂钩中调用的方法,而不在“ shallowMount”中使用已弃用的“ methods”参数?

时间:2020-09-25 21:33:17

标签: typescript vue.js jestjs vue-test-utils

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

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

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()传递到methods的情况下模拟shallowMount()挂钩中调用的方法来解决弃用警告?

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

按照警告的建议,我意识到我可以导入该方法并对其进行模拟以进行测试,但是我正在寻找一种替代方法,尤其是在这种情况下,这种方法会显得过大。

注意:链接的“重复”问题与答案无法回答我的问题,请投票以重新打开或以其他方式解释为什么已在评论中将其关闭

1 个答案:

答案 0 :(得分:0)

哇,我什至都不知道它已被弃用。这也是我一直在测试mounted期间调用的方法的方式,所以这就是我所发现的。就个人而言,我会选择第一个选择。

如果您愿意更改测试理念,但不希望更改编码风格:

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

Source

否则,如果您愿意更改编码风格而不是测试理念:

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

Source

其他人建议消除错误:

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

config.showDeprecationWarnings = false;

...但是我认为这可能会导致更多的问题,而不是要解决的问题。如果不是现在,那么以后。除非您的项目决定永远不更新到我想的新Vue版本?

这些是我能够找到的唯一解决方案。我希望我能找到一个更好的答案。如果我们可以在createdmounted之间停下来并模拟一个方法,那将是很好的选择,但是我什至不知道该方法对象当时是否存在,而且我不知道如何查找

相关问题