9

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

Yuta
  • 91
  • 1
  • 3
  • Can you provide some reproducible examples? Why do you need `shallowMount` if you want to call `search` anyway? – vovchisko Mar 15 '21 at 16:16
  • Because this component is a container component that has two child components(search box, table). This component is only dealing with data(provided by API). – Yuta Mar 15 '21 at 16:49
  • Facing same problem, I would like to fetch API data from created() or mounted() hook using async/await. To me it seems that shallowMount is not async function, so await does not work there. Currently im using ugly workaround with setTimeout that wait few seconds, after that data from API are delivered, even mounted() or created() hook is invoked synchronously. Pretty terrible. Im really interested what is better way to do that. – n0hepe Mar 26 '21 at 18:56

1 Answers1

5

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...
Eduardo
  • 1,086
  • 5
  • 19
  • You could also use `await jest.runAllTimers()`, if you don't want to add `flush-promises` to your project. – Mike C Mar 02 '22 at 17:59
  • I think that ```await jest.runAllTimers()``` is a kind of a hack, so I'd stick to the ```flush-promises``` library. – Eduardo Aug 29 '22 at 08:22
  • I was waiting for runAllTimers but it didn't work. flush-promises solved my case in particular. – Eduardo Sousa Dec 26 '22 at 17:28