如何Mock SQS客户端而非客户端函数?单元测试场景求助
Got it, you want to mock the entire AWS SQS client (not just individual methods) to unit test your SQSHealthCheckStrategy class—smart move for keeping your tests isolated and fast. Let's break down how to do this using Jest (the approach works similarly with other frameworks like Sinon too).
SQSHealthCheckStrategy Tests 1. Mock the Entire AWS.SQS Class
Instead of mocking just the getQueueUrl method, we'll mock the full AWS.SQS constructor to return a controlled client instance. This lets us define exactly how the client behaves across different test scenarios.
Here's how to set up the mock in Jest:
// Mock the AWS SDK module jest.mock('aws-sdk', () => { // Create a mock getQueueUrl method we can manipulate per test const mockGetQueueUrl = jest.fn(); // Return a mock SQS class that generates our controlled client return { SQS: jest.fn(() => ({ getQueueUrl: mockGetQueueUrl // Add other client methods here if your class uses them later })) }; });
2. Set Up Test Boilerplate
Before writing individual test cases, we'll create a reusable setup to reset mocks, set environment variables, and initialize our class under test:
import AWS from 'aws-sdk'; import SQSHealthCheckStrategy from './your-file-path'; // Replace with your actual file path describe('SQSHealthCheckStrategy', () => { let mockSqsClient; let healthCheck; beforeEach(() => { // Reset all mocks to avoid cross-test contamination jest.clearAllMocks(); // Set the required queue URL environment variable process.env.AWS_QUEUE_URL = 'test-queue-123'; // Create our mock client and initialize the health check class mockSqsClient = new AWS.SQS(); healthCheck = new SQSHealthCheckStrategy(mockSqsClient); });
3. Test Success Scenario
When getQueueUrl resolves without an error, your check() method should return true:
it('returns true when SQS queue is reachable', async () => { // Mock the getQueueUrl.promise() to resolve with a successful response mockSqsClient.getQueueUrl.mockReturnValue({ promise: jest.fn().mockResolvedValue({ $response: { error: null } // No error in the AWS response }) }); const result = await healthCheck.check(); expect(result).toBe(true); // Verify the client was called with the correct queue name expect(mockSqsClient.getQueueUrl).toHaveBeenCalledWith({ QueueName: process.env.AWS_QUEUE_URL }); });
4. Test Failure Scenarios
We need to cover two common failure cases: a response with an error, and a thrown exception.
Case 1: Response Contains an Error
it('returns false when SQS returns an error in the response', async () => { mockSqsClient.getQueueUrl.mockReturnValue({ promise: jest.fn().mockResolvedValue({ $response: { error: new Error('Queue not found') } // Simulate AWS response error }) }); const result = await healthCheck.check(); expect(result).toBe(false); });
Case 2: Client Throws an Exception
it('handles exceptions thrown by the SQS client', async () => { const testError = new Error('AWS service unavailable'); mockSqsClient.getQueueUrl.mockReturnValue({ promise: jest.fn().mockRejectedValue(testError) }); const result = await healthCheck.check(); // Adjust this expectation based on your catch block logic // For example, if you return false in the catch, assert that here expect(result).toBe(false); }); });
Key Tips
- By mocking the full
AWS.SQSclass, you eliminate dependencies on real AWS services—making tests fast and reliable. - Always reset mocks between tests to ensure each test starts with a clean state.
- If your class uses other SQS methods later, just add them to the mock client object in the initial
jest.mocksetup.
内容的提问来源于stack exchange,提问作者TovrikTheThird

