我正在运行 Jest 测试来测试 dynamodb.js 文件和使用 dynamodb.js 文件的 create.js 文件。 create.js 模块是通用的,可以通过构造 param 对象并将其传递到其中来插入到任何表中。但是,我收到以下错误,我需要帮助。
TypeError: AWS.DynamoDB.DocumentClient is not a constructor
__mock__
folder
const getMock = jest.fn().mockImplementation(() => {
return {
promise() {
return Promise.resolve({});
}
};
});
const putMock = jest.fn().mockImplementation(() => {
return {
promise() {
return Promise.resolve({});
}
};
});
// eslint-disable-next-line func-names
function DynamoDB() {
return {
DocumentClient: jest.fn(() => ({
get: getMock,
put: putMock
}))
};
}
const AWS = { DynamoDB, getMock, putMock };
module.exports = AWS;
dynamodb.js
const AWS = require('aws-sdk');
const http = require('http');
const https = require('https');
const url = require('url');
module.exports = endpoint => {
const { protocol } = url.parse(endpoint || '');
const agentConfig = {
keepAlive: true,
keepAliveMsecs: 20000
};
const httpOptions =
protocol === 'http:' ? { agent: new http.Agent(agentConfig) } : { agent: new https.Agent(agentConfig) };
const db = new AWS.DynamoDB({
endpoint,
httpOptions
});
const docClient = new AWS.DynamoDB.DocumentClient({
service: db
});
return {
docClient,
db
};
};
dynamodb.spec.js
const AWS = require('aws-sdk');
const dynamodb = require('../../../src/dynamodb');
describe('dynamodb.js', () => {
beforeEach(() => {
// jest.resetModules();
});
test('calls generic-dynamodb-lib dynamodb', async () => {
dynamodb('http://localhost:8001');
expect(AWS.DynamoDB).toHaveBeenCalled();
expect(AWS.DynamoDB.DocumentClient).toHaveBeenCalled();
});
});
create.js
// Imports here
const create = async (log, docClient, table, tableRecord) => {
try {
await docClient.put({ TableName: table, Item: tableRecord }).promise();
} catch (error) {
log.error({ message: 'DynamoDB error', ...error });
throw Error.internal();
}
return tableRecord;
};
module.exports = create;
我还尝试用 doMock block 替换 mock 中的手动模拟,但仍然继续出现上述相同的错误。 一旦我克服了这个问题,考虑到 docClient.js 被传递到函数中,我如何测试 create.js ?非常感谢。
最佳答案
DocumentClient
应该是静态属性,但它被模拟为实例属性。
应该是:
const DynamoDB = jest.fn().mockReturnValue({});
DynamoDB.DocumentClient = jest.fn().mockReturnValue({
get: getMock,
put: putMock
});
关于javascript - 使用 Jest 测试时,类型错误 : AWS. DynamoDB.DocumentClient 不是构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62672707/