我正在尝试在jest
中模拟aws-sdk
。
我在<root>utilsjest__mocks__mock-aws-sdk.js
中有以下代码。
const AWS = require('aws-sdk');
jest.mock('aws-sdk', () => ({
config: {
update: jest.fn(),
},
EventBridge: jest
.fn()
.mockImplementation(() => ({
describeRule: mockDescribeRule,
})),
Lambda: jest
.fn()
.mockImplementation(() => ({
invoke: mockInvoke,
})),
DynamoDB: jest
.fn({
DocumentClient: jest.fn(),
getItem: jest.fn(),
batchWrite: jest.fn(),
batchGetItem: jest.fn(),
}),
}));
// And the mock implementation
const mockDescribeRule = jest.fn().mockImplementation((rule) => ({
Name: rule.Name,
}));
...
使用上面的代码,我在运行npm run jest:coverage -- -u
:时出错
TypeError: AWS.DynamoDB.DocumentClient is not a constructor
当我添加以下行时:
AWS.DynamoDB.DocumentClient = jest.fn().mockImplementation(() => ({
}));
我得到以下错误:
ConfigError: Missing region in config
我不确定如何在node.js
中成功模拟aws-sdk
我认为这可能适用于您仍在搜索答案的情况
jest.mock('aws-sdk', () => ({
...jest.mock('aws-sdk'),
DynamoDB: jest.fn().mockImplementation(() => {
return {
DocumentClient: jest.fn(),
getItem: jest.fn(),
batchWrite: jest.fn(),
batchGetItem: jest.fn(),
};
}),
}));