Don*_*n P 6 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.
Run Code Online (Sandbox Code Playgroud)
测试组件.Vue:
...
created() {
doSomething();
}
...
methods: {
doSomething(): void { /* do something */ }
}
Run Code Online (Sandbox Code Playgroud)
测试组件.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
});
}
Run Code Online (Sandbox Code Playgroud)
如何模拟挂钩中调用的方法created()而不传递methodstoshallowMount()来解决弃用警告?
或者,有没有办法模拟或绕过created()生命周期挂钩?
根据警告建议,我意识到我可以导入该方法并模拟它进行测试,但我正在寻找替代方案,特别是在这种情况下会太过分。
哇,我什至不知道它已被弃用。这也是我测试期间调用的方法的方式mounted,所以这是我发现的。就我个人而言,我会选择第一个选项。
如果您愿意改变您的测试理念,但不想改变您的编码风格:
我想解决方案是不测试这些方法是否被调用,而是测试它们的效果是否被应用。这一切都很好,直到您处理 DOM(其中 Jest/JSDOM 在某些情况下严重缺乏功能)。
另外,如果您愿意改变编码风格但不愿意改变测试理念:
我立即想到的一个解决方法(可能不理想)是将所述方法放入另一个文件中并导入它。那么你就可以使用
jest.mock.
其他人建议消除错误:
import { config } from '@vue/test-utils';
config.showDeprecationWarnings = false;
Run Code Online (Sandbox Code Playgroud)
...但我认为这可能会导致比解决的问题更多的问题。如果不是现在,那就以后吧。我想除非你的项目决定永远不更新到较新的 Vue 版本?
这些是我能够挖掘的唯一解决方案。我希望我能找到更好的答案。created如果我们可以在和之间暂停并模拟一个方法,那就太好了mounted,但我什至不确定该方法对象此时是否存在,而且我不知道如何找出答案。
| 归档时间: |
|
| 查看次数: |
2459 次 |
| 最近记录: |