Jest/Node.js -模拟类的示例方法的问题

xsuvu9jc  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(178)

我有一个脚本,我在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()


我这样嘲笑我的文档方法:

jest.mock('@model/documentModel', () => {
  return {
    Document: jest.fn().mockImplementation(() => ({
      create: jest.fn().jest.fn().mockImplementation(() => mockedDocument)),
    })),
  };
});


因为我希望create方法返回mockedDocument,但当我运行测试时,我收到以下错误:

Error: Document is not a constructor, Stack: TypeError: Document is not a constructor


有人知道怎么修吗?

yqkkidmi

yqkkidmi1#

你会想要像下面这样把东西连接起来:

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);

相关问题