Vue-test-utils doesn't wait for the response from the API request

Viewed 1198

I've been really struggling to do something very simple. I have to write some tests for a Vue application.

The scenario I want to test is the following:

  1. The user fills in a form
  2. The user submits the form
  3. The values from the form are sent to the backend in one object
  4. The server responds with an object containing the fields of the object it has received in the request (plus some new fields).
  5. The Vue app stores the result in the Vuex store

I want my test to check if, after the form has been validated, the request is made and the returned values are properly stored in the store.

This is super basic, but for some reason I can't get the test to work.

I have a globally registered component that makes axios accessible by using this.api.
So in my test, I have the following (the file is simplified for this post):

...
import axios from 'axios';
import AxiosMockAdapter from 'axios-mock-adapter';
import flushPromises from 'flush-promises';

// This is the axios setup used in the components
import api from '../../src/mixins/api';

// Components
import MyComponent from '../component.vue';

describe('MyComponent', () => {
  // Set up the local vue
  ...

  const wrapper = mount(MyComponent, {
    localVue,
    ...
  });

  beforeEach(() => {
    const instance = axios.create({
      baseURL: 'some/url/',
    });
    wrapper.vm.api = new AxiosMockAdapter(instance);
    wrapper.vm.api.onPost('url/').replyOnce(201, { data: { foo: 'bar' } });
  });

  it('should retrieve the data', async () => {
     wrapper.find('#submit').trigger('click');

    await flushPromises();
    expect(wrapper.vm.$store.state.foo !== undefined).toBe(true);
  });
});

But the test isn't successful. I think the request is made properly, but by the time the test reaches its end the response hasn't be received yet. And this is despite using flushPromises(). I also tried to use setTimeout but with no success neither.

I'm new to unit testing (especially on front end apps) and I have no idea what else to try. Nothng works... It's very frustrating because what I'm tryng to do is pretty straight forward and basic.

Anyone has an idea what to do ?

0 Answers
Related