NOTE: the linked "duplicate" question & answer does NOT answer my question, please vote to reopen or otherwise explain why this has been closed in comments
I have a created()
hook that calls doSomething()
method. I can get the tests to pass by passing the methods
param to shallowMount()
and overiding with jest.fn()
.
However when I take this approach I receive the deprecation warnings regarding 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
});
}
How can I mock the method called in the created()
hook without passing methods
to shallowMount()
to resolve the deprecation warnings?
Alternatively, is there a way to either mock or bypass the created()
lifecycle hook?
Per the warning suggestion, I realize I could import the method and mock it for tests but I am looking for an alternative especially in cases where that would be overkill.
Wow, I didn't even know this was deprecated. This is the way I have been testing methods called during
mounted
too, so here is what I found. Personally I'll go with the first option going forward.If you're willing to change your testing philosophy but not your coding style:
Else, if you're willing to change your coding style but not your testing philophy:
Someone else recommended silencing the errors:
...But I think that could cause more problems than it would fix. If not now, then later. Unless your project decides to never update to newer Vue versions I suppose?
These are the only solutions I was able to dig up. I wish I could have found a better answer. It would be nice if we could pause somewhere between
created
andmounted
and mock a method, but I'm not even sure whether the methods object exists at that point and I don't know how to find out.