composition-api icon indicating copy to clipboard operation
composition-api copied to clipboard

fix: useFetch in jest unit tests

Open FloryanFilip opened this issue 3 years ago • 6 comments

🐛 The bug When unit testing a component that uses useFetch composable, I'm getting weird error. Zrzut ekranu 2021-04-2 o 22 29 09 Zrzut ekranu 2021-04-2 o 22 29 15

🛠️ To reproduce Steps to reproduce the behavior:

  1. Create a component that uses setup function with useFetch composable inside of it
  2. Write a test suite with any unit test of said component
  3. See error

I'd be very grateful for a link to a gist or repo that reproduces the bug.

🌈 Expected behaviour The test suite runs smoothly

ℹ️ Additional context My component

export default defineComponent({
  setup() {

    const { fetch } = useFetch(async () => {
      //
    });

    return {
      //
    };
  },

My test suite


describe('MainSearch', () => {
  let wrapper!: Wrapper<any>;
  const factory = (data?: object) => shallowMount(MainSearchComponent, {
    stubs: {
      ...
    },
    vuetify: new Vuetify(),
  });

  beforeEach(() => {
    wrapper = factory();
  });

  afterEach(() => {
    wrapper.destroy();
  });

  it('should match snapshot', () => {
    expect(wrapper.html())
      .toMatchSnapshot();
  });

FloryanFilip avatar Apr 02 '21 20:04 FloryanFilip

@FloryanFilip I can't reproduce the error with your code. Note that useFetch is quite tightly coupled with Nuxt and it needs a number of global properties to be present on the instance in order to actually execute fetch(), which is probably why you're getting these errors (though not in your code snippets above).

danielroe avatar Apr 12 '21 12:04 danielroe

@danielroe what do you mean by number of global properties? How can I make sure i have these?

FloryanFilip avatar Apr 20 '21 08:04 FloryanFilip

I would also be interested in what setup steps are missing. I created a reproduction repo here

treebee avatar Apr 26 '21 12:04 treebee

I'm facing the same issue! any updates on this @danielroe ?

jesus4497 avatar May 26 '22 16:05 jesus4497

Any updates ? Same issue.

ashish141199 avatar Nov 20 '22 09:11 ashish141199

Yea, same here. Can't test a composable with "useFetch" inside.

The useFetch don't execute outside of setup env.

odranoelBR avatar May 04 '23 23:05 odranoelBR