How to avoid rerenders in a Vue component while testing using Jest

29 Views Asked by At

I'm trying to test a VueJS application using Jest and Vue Test Utils. Now the tests seem to have been properly written, and the component itself is working fine.

When I run my test it seems to be rerendering the component (for a lack of better words) right before the first API call. I've added a couple of console.log statements to see what the flow of the code is. Right before making the API call, it will restart at the setup hook.

When I start the dev server in the browser it just works...

This is my test:

describe('When all data is fetched successfully', () => {
const fetchAnimalMethod = jest.spyOn(AnimalDetail.methods, 'fetchAnimal');

  const wrapper = getWrapper();

  beforeEach(async () => {
    await flushPromises();
  });

  test('All API fetch methods should have been called', async () => {
    expect(fetchAnimal)
      .toHaveBeenCalledTimes(1);
  });
});

I am using the mounted lifecycle hook to call a method which calls the API. The returned value of that API call is then assigned to a data variable.

Below is an abstract of that logic in my code:

async mounted() {
    try {
      console.log("a")
      this.animal = await this.fetchAnimal(this.animalId);
} catch (error) {
this.handleError(error)
console.log(error)
}

When I run this in the browser the API call is made just once, so all good.

Does anyone know why the API call is made seven times when I run it in my test?

0

There are 0 best solutions below