Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async lifecycle function in Vue Test Utils

When I tried to test the component which has mounted method like this:

mounted(){
this.search()
}

methods:{
  async search(){
     try{
       await axios.something
       console.log("not executed only when shallowMount")
      }catch{}
  }
}

I checked it returned Promise<pending> without await.
I wrote the test like this:

    wrapper = await shallowMount(Component, {
      localVue
    });
    await wrapper.vm.search()// this works perfectly

However, only the shallowMount apparently skips awaited function while the next line works perfectly.
I have no idea about this behavior.
How can I fix it?

Edit:

I also use Mirage.js for mocking response.

function deviceServer() {
  return createServer({
    environment: "test",
    serializers: {
      device: deviceListSerializer()
    },
    models: {
      device: Model
    },
    fixtures: {
      devices: devices
    },
    routes() {
      this.namespace = "/api/v1/";
      this.resource("device");
    },
    seeds(server) {
      server.loadFixtures("devices");
    }
  });
}

like image 736
Yuta Avatar asked May 28 '26 23:05

Yuta


1 Answers

shallowMount is not returning Promise and that's why there is nothing to await. To await promises in tests try to use flush-promises library. With flushPromises your test will look like this:

import flushPromises from 'flush-promises'

wrapper = shallowMount(Component, {
      localVue
    });
await flushPromises(); // we wait until all promises in created() hook are resolved
// expect...
like image 168
Eduardo Avatar answered Jun 01 '26 16:06

Eduardo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!