如何解决如何在Jest单元测试中模拟在“ created” Vue生命周期挂钩中调用的方法,而不在“ shallowMount”中使用已弃用的“ methods”参数?
我有一个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()
生命周期挂钩?
按照警告的建议,我意识到我可以导入该方法并对其进行模拟以进行测试,但是我正在寻找一种替代方法,尤其是在这种情况下,这种方法会显得过大。
注意:链接的“重复”问题与答案无法回答我的问题,请投票以重新打开或以其他方式解释为什么已在评论中将其关闭
解决方法
哇,我什至都不知道它已被弃用。这也是我一直在测试mounted
期间调用的方法的方式,所以这就是我所发现的。就个人而言,我会选择第一个选择。
如果您愿意更改测试理念,但不希望更改编码风格:
我猜解决方案是不测试是否调用了这些方法,而是测试它们的效果是否适用。除非您处理DOM(在某些情况下Jest / JSDOM严重缺乏功能),否则一切都很好。
否则,如果您愿意更改编码风格而不是测试理念:
想到的一个立即解决的方法(可能不理想)是将所述方法放在另一个文件中并导入它。然后,您可以使用
jest.mock
。
其他人建议消除错误:
import { config } from '@vue/test-utils';
config.showDeprecationWarnings = false;
...但是我认为这可能会导致更多的问题,而不是要解决的问题。如果不是现在,那么以后。除非您的项目决定永远不更新到我想的新Vue版本?
这些是我能够找到的唯一解决方案。我希望我能找到一个更好的答案。如果我们可以在created
和mounted
之间停下来并模拟一个方法,那将是很好的选择,但是我什至不知道该方法对象当时是否存在,而且我不知道如何查找
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。