【问题标题】:How to mock method called in `created` Vue lifecycle hook in Jest unit test without using deprecated `methods` param in `shallowMount`? [duplicate]如何在 Jest 单元测试中模拟在 `created` Vue 生命周期挂钩中调用的方法,而不使用`shallowMount` 中已弃用的`methods` 参数? [复制]
【发布时间】:2021-01-12 05:28:43
【问题描述】:

注意:链接的“重复”问题和答案没有回答我的问题,请投票重新打开或以其他方式解释为什么在 cmets 中关闭了此问题

我有一个调用doSomething() 方法的created() 钩子。我可以通过将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
    });
}

如何在不将methods 传递给shallowMount() 的情况下模拟created() 挂钩中调用的方法来解决弃用警告?

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

根据警告建议,我意识到我可以导入该方法并对其进行模拟以进行测试,但我正在寻找一种替代方法,尤其是在这种情况下过度杀伤的情况下。

【问题讨论】:

  • 链接的“重复”没有回答我的问题。不知道为什么关闭。

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


【解决方案1】:

哇,我什至不知道这已被弃用。这也是我测试mounted 期间调用的方法的方式,所以这就是我发现的。就我个人而言,我将继续使用第一个选项。

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

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

Source

另外,如果你愿意改变你的编码风格而不是你的测试理念:

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

Source

其他人建议消除错误:

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

config.showDeprecationWarnings = false;

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

这些是我能够挖掘的唯一解决方案。我希望我能找到更好的答案。如果我们可以在 createdmounted 之间暂停并模拟一个方法,那就太好了,但我什至不确定该方法对象是否存在,我不知道如何找到。

【讨论】:

    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 2021-01-25
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多