In my Vue2
component, I have an asynchronous lifecycle hook method:
// create report when component is loading
async mounted(): Promise<void> {
await this.createReport();
}
Now, I want to test my component using jest
and vue/test-utils
, but the test needs to wait for the completion of the mounted()
method.
const wrapper = await mount(MyComponent, { // <-- no Promise, await has no effect
localVue
});
await flushPromises(); // <-- is not waiting for the async mounted()
expect(wrapper.vm.currentReport.sections).toHaveLength(5); // <-- failing since createReport not finished
Unfortunately, both mount()
and shallowMount()
do not return a Promise
and do not wait for the lifecycle hook to complete.
Currently, the only workaround has been using await flushPromises()
, which doesn't affect the mounted method.
Some have suggested using await mount()
even though it doesn't return a Promise, but this also doesn't have any impact in this scenario.
It seems that most tests pass because they are fast enough for the mounted method to finish before checking assertions.
However, in cases where data loading takes longer, like a few seconds, this approach falls short.
While users see a loading screen and patiently wait for the component to be ready, jest does not have the same patience.
How can I ensure that my Vue tests with jest start only after the mounted logic has completed?