How to mock an interface function in Vitest?

342 Views Asked by At

I have a function that calls AbortSignal.timeout(8000); inside ~~/src/config/fetch.ts. In my Vitest test files I can't seem to mock it.

I keep getting the error TypeError: AbortSignal.timeout is not a function.

I have tried the following:

  vi.spyOn(AbortSignal, 'timeout').mockImplementation(() => ({
    timeout: () => {},
  }));

And

vi.spyOn(AbortSignal, 'timeout').mockResolvedValue({});

And

  vi.mock('~~/src/config/fetch', () => {
    return {
      AbortSignal: {
        timeout: () => {},
      },
    };
  });

Also tried this:

  vi.mock('~~/src/config/fetch', async () => {
    const actual: Object = await vi.importActual('~~/src/config/fetch');
    return {
      ...actual,
      setOptionSignal: () => {},
    };
  });

const setOptionSignal = () => {
  return AbortSignal.timeout(8000);
};

options.signal = setOptionSignal();

But it can not find AbortSignal.timeout to mock it. My best guess is because it is a function from an interface.

What am I doing wrong?

0

There are 0 best solutions below