Skip to content

Vitest mocking isn't working using tsx (esm target) #475

@OlivierCuyp

Description

@OlivierCuyp

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

5.6.0

Plugin version

6.3.1

Node.js version

24.7.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

15.6.1

Description

Testing my app using fastify & autoload I just can't mock anything.
It is always the original code that is called.

Here is the concerned piece of code.

src/helpers/testHelper.ts

const run = () => {
  return 'REAL';
};

export const testMock = { run };

src/routes/test/testHanlder.ts

import type { FastifyInstance } from 'fastify';

import { testMock } from '@/helpers/testHelper.ts';

export default async (app: FastifyInstance) => {
  app.get('', async (_request, reply) => {
    const result = testMock.run();
    reply.send({ result });
  });
};

test/server.ts

import { describe, expect, it, vi } from 'vitest';
import { testMock } from '@/helpers/testHelper.ts';

import { createApp } from '../src/server.ts';

describe('server api', () => {
  it('should mock', async () => {
    vi.spyOn(testMock, 'run').mockImplementation(() => {
      return 'MOCK';
    });

    const res = await createApp().inject({
      method: 'GET',
      url: '/test'
    });

    expect(res.statusCode).toEqual(200);
    expect(res.json()).toEqual({
      result: 'MOCK'
    });
  });
});

Test

FAIL  test/server.ts > server api > should mock
AssertionError: expected { result: 'REAL' } to deeply equal { result: 'MOCK' }

- Expected
+ Received

  {
-   "result": "MOCK",
+   "result": "REAL",
  }

 ❯ test/server.ts:27:24
     25| 
     26|     expect(res.statusCode).toEqual(200);
     27|     expect(res.json()).toEqual({
       |                        ^
     28|       result: 'MOCK'
     29|     });

See MRE

Link to code that reproduces the bug

https://github.com/OlivierCuyp/fastify-autoload-vitest-esm-mock

Expected Behavior

Mock should be applied and test should pass.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions