[Vuejs]-How to write a unit test with data fetching, that alters data based on respone in vuejs?

0👍

Code that running inside getSomething() is asynchronous. MyService.getThis() returns promise, and its execution takes time, in case if you fetching some data from remote serivce.

So first of all you need to return promise from getSomething()

getSomething() {
  return MyService.getThis()
    .then(response => { this.status = true; })
    .catch(error => {})
}

And inside the test you need to return promise outside, to let jest know that your test is asynchronous.

it('should work', () => {
  return wrapper.vm.getSomething().then(() => {
    expect(wrapper.vm.status).toBeTruthy();
  });
});

Or as you mentioned in the edited part you can use async version:

it('should work', async () => {
  await getSomething();
  expect(wrapper.vm.status).toBeTruthy();
});

Leave a comment