Вы можете использовать jest.mock (moduleName, factory, options) для макетирования aws-sdk
пакета, Comprehend
класса и методов его экземпляра.
Например
index.ts
:
import AWS from 'aws-sdk';
const comprehend = new AWS.Comprehend();
export const handler = async (): Promise<any> => {
const params = {
JobName: 'first-job',
InputDataConfig: {
S3Uri: 'input_bucket_name',
InputFormat: 'ONE_DOC_PER_FILE',
},
OutputDataConfig: {
S3Uri: 'output_bucket_name',
},
DataAccessRoleArn: 'role_arn',
};
const result = await comprehend
.startDominantLanguageDetectionJob(params)
.promise()
.catch((error) => {
throw error;
});
return result.JobId;
};
index.test.ts
:
import MockAWS from 'aws-sdk';
import { handler } from './';
jest.mock('aws-sdk', () => {
const mComprehend = {
startDominantLanguageDetectionJob: jest.fn().mockReturnThis(),
promise: jest.fn(),
};
return {
Comprehend: jest.fn(() => mComprehend),
};
});
describe('61497560', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should return job id', async () => {
const mComprehend = new MockAWS.Comprehend();
const mResponse = { JobId: 1 };
(mComprehend.startDominantLanguageDetectionJob().promise as jest.Mocked<any>).mockResolvedValueOnce(mResponse);
const actual = await handler();
expect(actual).toBe(1);
expect(mComprehend.startDominantLanguageDetectionJob).toBeCalledWith({
JobName: 'first-job',
InputDataConfig: {
S3Uri: 'input_bucket_name',
InputFormat: 'ONE_DOC_PER_FILE',
},
OutputDataConfig: {
S3Uri: 'output_bucket_name',
},
DataAccessRoleArn: 'role_arn',
});
expect(mComprehend.startDominantLanguageDetectionJob().promise).toBeCalledTimes(1);
});
it('should throw error', async () => {
const mComprehend = new MockAWS.Comprehend();
const mError = new Error('network');
(mComprehend.startDominantLanguageDetectionJob().promise as jest.Mocked<any>).mockRejectedValueOnce(mError);
await expect(handler()).rejects.toThrow('network');
expect(mComprehend.startDominantLanguageDetectionJob).toBeCalledWith({
JobName: 'first-job',
InputDataConfig: {
S3Uri: 'input_bucket_name',
InputFormat: 'ONE_DOC_PER_FILE',
},
OutputDataConfig: {
S3Uri: 'output_bucket_name',
},
DataAccessRoleArn: 'role_arn',
});
expect(mComprehend.startDominantLanguageDetectionJob().promise).toBeCalledTimes(1);
});
});
Результаты модульного теста со 100% покрытием:
PASS stackoverflow/61497560/index.test.ts (10.06s)
61497560
✓ should return job id (8ms)
✓ should throw error (2ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 11.292s