提问人:Rafael Polonio 提问时间:11/18/2023 更新时间:11/18/2023 访问量:16
Jest/Node.js - 模拟类的实例方法时出现问题
Jest/Node.js - Problems mocking a instance method of a class
问:
我有一个脚本,我在 dynamoDB 的文档表中创建了一条记录。 这个创建方法是从我的 documentModel 调用的,如下所示:
class Document {
constructor(props) {
this['createdAt'] = Date.now()
this['updatedAt'] = Date.now()
this['isDeleted'] = false
this['isUploaded'] = false
this['isDownloaded'] = false
Object.keys(props).forEach((key) => {
this[key] = props[key]
})
this['signalTrackerId'] = getRequestContext().signalTrackerId
}
async create() {
const params = {
TableName,
Item: { ...this },
ConditionExpression: `attribute_not_exists(fileName)`,
}
return dynamodb.insertItem(params).catch((err) => {
if (err.code === 'ConditionalCheckFailedException') {
throw new TraytError('debug')
.setCode(1002)
.setDetails({ message: 'FileName already exists' })
}
throw new TraytError('error', err)
.setCode(1002)
.setDetails({ message: 'Unknown DynamoDB error' })
})
}
并在此处从我的脚本中调用:
const Document = require('@model/documentModel')
const createDocumentAndReferral = async (input) => {
const document = new Document({
recordId,
fileName: `regression-test___${recordId}.jpg`,
})
await document.create()
我像这样嘲笑我的 Document 方法:
jest.mock('@model/documentModel', () => {
return {
Document: jest.fn().mockImplementation(() => ({
create: jest.fn().jest.fn().mockImplementation(() => mockedDocument)),
})),
};
});
因为我希望创建方法返回mockedDocument,但是当我运行测试时,我收到以下错误:
Error: Document is not a constructor, Stack: TypeError: Document is not a constructor
有人知道如何解决吗?
答:
0赞
Wil Moore III
11/18/2023
#1
您需要像下面这样连接内容:
const document = new Document({
recordId,
fileName: `regression-test___${recordId}.jpg`,
})
mockCreate = jest.spyOn(document, 'create').mockImplementation(() => {
return Promise.resolve(mockedDocument);
});
艺术
const document = new Document({
recordId,
fileName: `regression-test___${recordId}.jpg`,
});
document.create = jest.fn().mockResolvedValue(mockedDocument);
评论
1赞
Rafael Polonio
11/18/2023
我应该删除jest.mock('@model/documentModel')的东西吗?
0赞
Wil Moore III
11/18/2023
这是正确的@RafaelPolonio。其目的是创建单独的模拟函数来模拟回调,或作为要在测试期间监视或控制其行为的函数的占位符。jest.fn()
评论