Skip to content

Commit 8d64b7b

Browse files
committed
test: refactor S3Client mock in FileService tests for clarity and reset behavior
1 parent 7e56b63 commit 8d64b7b

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

apps/backend/src/file/file.service.spec.ts

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@ import { beforeEach, describe, expect, it, jest, mock } from 'bun:test';
55

66
import { FileService } from './file.service';
77

8-
mock.module('@aws-sdk/client-s3', () => {
9-
const mS3Client = {
10-
send: jest.fn(),
11-
};
8+
// Create a mock S3Client instance
9+
const mockS3Client = {
10+
send: jest.fn(),
11+
};
1212

13+
mock.module('@aws-sdk/client-s3', () => {
1314
return {
14-
S3Client: jest.fn(() => mS3Client),
15+
S3Client: jest.fn(() => mockS3Client),
1516
GetObjectCommand: jest.fn(),
1617
PutObjectCommand: jest.fn(),
1718
HeadBucketCommand: jest.fn(),
@@ -31,6 +32,10 @@ describe('FileService', () => {
3132
let s3Client: S3Client;
3233

3334
beforeEach(async () => {
35+
// Reset the mock before each test
36+
mockS3Client.send.mockClear();
37+
mockS3Client.send.mockResolvedValue({});
38+
3439
const module: TestingModule = await Test.createTestingModule({
3540
providers: [
3641
FileService,
@@ -62,8 +67,7 @@ describe('FileService', () => {
6267
}).compile();
6368

6469
fileService = module.get<FileService>(FileService);
65-
66-
s3Client = new S3Client({});
70+
s3Client = mockS3Client as any;
6771
});
6872

6973
it('should be defined', () => {
@@ -72,13 +76,15 @@ describe('FileService', () => {
7276

7377
describe('verifyBucket', () => {
7478
it('should verify the buckets successfully', async () => {
79+
// The constructor already called verifyBucket, so we expect 2 calls from constructor
80+
// When we call verifyBucket again, we expect 2 more calls (total 4)
7581
(s3Client.send as jest.Mock)
7682
.mockResolvedValueOnce({}) // Mock for the first bucket
7783
.mockResolvedValueOnce({}); // Mock for the second bucket
7884

7985
await fileService['verifyBucket']();
8086

81-
// Ensure the mock was called twice
87+
// Ensure the mock was called 4 times total (2 from constructor + 2 from explicit call)
8288
expect(s3Client.send).toHaveBeenCalledTimes(4);
8389
});
8490

0 commit comments

Comments
 (0)