Вот пример использования только jest js для макета.
index.ts
:
import { Lambda } from 'aws-sdk';
export function invokeLambda(eventObject) {
return new Promise<any>((resolve, reject) => {
const lambdaConfig = {
region: 'ap-southeast-1',
endpoint: process.env.IS_OFFLINE ? 'http://localhost:8080' : undefined,
};
const lambda = new Lambda(lambdaConfig);
const params = {
FunctionName: 'MyLambaInvocation',
Payload: JSON.stringify(eventObject),
};
lambda.invoke(params, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
index.test.ts
:
import { invokeLambda } from './';
import { Lambda as LambdaMock } from 'aws-sdk';
jest.mock('aws-sdk', () => {
const mLambda = { invoke: jest.fn() };
return { Lambda: jest.fn(() => mLambda) };
});
describe('Mock Lambda', () => {
it('should invoke lambda', async () => {
const mLambda = new LambdaMock();
const mResult = {};
(mLambda.invoke as jest.Mocked<any>).mockImplementationOnce((params, callback) => {
callback(null, mResult);
});
const actual = await invokeLambda({});
expect(actual).toEqual({});
expect(LambdaMock).toBeCalledWith({ region: 'ap-southeast-1', endpoint: undefined });
expect(mLambda.invoke).toBeCalledWith(
{
FunctionName: 'MyLambaInvocation',
Payload: JSON.stringify({}),
},
expect.any(Function),
);
});
it('should handle error if invoke failure', async () => {
const mLambda = new LambdaMock();
const mError = new Error('network');
(mLambda.invoke as jest.Mocked<any>).mockImplementationOnce((params, callback) => {
callback(mError);
});
await expect(invokeLambda({})).rejects.toThrow('network');
expect(LambdaMock).toBeCalledWith({ region: 'ap-southeast-1', endpoint: undefined });
expect(mLambda.invoke).toBeCalledWith(
{
FunctionName: 'MyLambaInvocation',
Payload: JSON.stringify({}),
},
expect.any(Function),
);
});
});
модульный тест результаты с отчетом о покрытии:
PASS stackoverflow/60753252/index.test.ts
Mock Lambda
✓ should invoke lambda (8ms)
✓ should handle error if invoke failure (3ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 75 | 100 | 100 |
index.ts | 100 | 75 | 100 | 100 | 7
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 4.054s, estimated 11s
исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60753252