fastify / fastify/fastify-autoload

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

Open
#475 11 comments 2 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
373
Forks
77
PR merge metrics
No merged PRs in 30d

Description

### Prerequisites

- [x] I have written a descriptive issue title
- [x] 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
```ts
const run = () => {
return 'REAL';
};

export const testMock = { run };
```

> src/routes/test/testHanlder.ts
```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
```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**

```sh
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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.