我有一個簡單的處理程式,呼叫 getData 定義在單獨的檔案中
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
let respData = await new DynamoDBClient().getData(123);
return {
statusCode: 200,
body: JSON.stringify(respData),
};
};
在我的 DynamoDB 類中,我有以下內容。
import { DynamoDB } from 'aws-sdk';
export default class DynamoDBClient {
private config: Config;
private client: DynamoDB.DocumentClient;
constructor() {
this.config = getConfig();
const dynamoDBClientConfig = this.config.mockDynamoDBEndpoint
? {
endpoint: this.config.mockDynamoDBEndpoint,
sslEnabled: false,
region: 'local'
}
: undefined;
this.client = new DynamoDB.DocumentClient(dynamoDBClientConfig);
}
// function
getData= async (id: string): Promise<any> => {
const response = await this.client
.query({
TableName: tableName,
IndexName: tableIndex,
KeyConditionExpression: 'id= :id',
ExpressionAttributeValues: {
':id': id
}
})
.promise();
return response;
}
}
我的測驗用例
describe('DynamoDB', () => {
test('should return no data', async () => {
const spy = jest.spyOn(DynamoDBClient, 'getData').mockImplementation(() => jest.fn(() => {
return Promise.resolve({});
}));
const actual = await handler(event);
console.log(actual);
expect(actual).toEqual({ statusCode: 400, body: JSON.stringify({ }) });
});
});
uj5u.com熱心網友回復:
您.getData()使用屬性初始值設定項語法定義了方法。它將系結到類實體。由于該handler函式DynamoDBClient通過import陳述句依賴于類,因此您無法在測驗用例中創建實體并handler在呼叫它時將其傳遞給它。
您可以模擬aws-sdk模塊和DynamoDB.DocumentClient類及其實體。
DynamoDBClient.ts:
import { DynamoDB } from 'aws-sdk';
function getConfig() {
return { mockDynamoDBEndpoint: '' };
}
interface Config {
mockDynamoDBEndpoint: string;
}
export default class DynamoDBClient {
private config: Config;
private client: DynamoDB.DocumentClient;
constructor() {
this.config = getConfig();
const dynamoDBClientConfig = this.config.mockDynamoDBEndpoint
? {
endpoint: this.config.mockDynamoDBEndpoint,
sslEnabled: false,
region: 'local',
}
: undefined;
this.client = new DynamoDB.DocumentClient(dynamoDBClientConfig);
}
getData = async (id: string): Promise<any> => {
const response = await this.client
.query({
TableName: 'tableName',
IndexName: 'tableIndex',
KeyConditionExpression: 'id= :id',
ExpressionAttributeValues: {
':id': id,
},
})
.promise();
return response;
};
}
handler.ts:
import DynamoDBClient from './DynamoDBClient';
interface APIGatewayProxyEvent {}
interface APIGatewayProxyResult {}
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
let respData = await new DynamoDBClient().getData('123');
return { statusCode: 200, body: JSON.stringify(respData) };
};
handler.test.ts:
import { handler } from './handler';
import { DynamoDB } from 'aws-sdk';
const mDocumentClientInstance = {
query: jest.fn().mockReturnThis(),
promise: jest.fn(),
};
jest.mock('aws-sdk', () => {
return {
DynamoDB: {
DocumentClient: jest.fn(() => mDocumentClientInstance),
},
};
});
describe('69475890', () => {
afterEach(() => {
jest.clearAllMocks();
});
test('should pass', async () => {
mDocumentClientInstance.promise.mockResolvedValueOnce({});
const event = {};
const actual = await handler(event);
expect(actual).toEqual({ statusCode: 200, body: JSON.stringify({}) });
expect(DynamoDB.DocumentClient).toBeCalled();
expect(mDocumentClientInstance.query).toBeCalledWith({
TableName: 'tableName',
IndexName: 'tableIndex',
KeyConditionExpression: 'id= :id',
ExpressionAttributeValues: {
':id': '123',
},
});
expect(mDocumentClientInstance.promise).toBeCalled();
});
});
測驗結果:
PASS examples/69475890/handler.test.ts (8.642 s)
69475890
? should pass (4 ms)
-------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------------|---------|----------|---------|---------|-------------------
All files | 100 | 50 | 100 | 100 |
DynamoDBClient.ts | 100 | 50 | 100 | 100 | 18
handler.ts | 100 | 100 | 100 | 100 |
-------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.231 s
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/316785.html
