Yuta
Yuta

Reputation: 91

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");
    }
  });
}

Upvotes: 9

Views: 4419

Answers (1)

Eduardo
Eduardo

Reputation: 1321

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...

Upvotes: 5

Related Questions