javascript Sinon无法存根不存在的自有属性“function”

8yparm6h  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(134)

我尝试模拟一个模块Database,这样它的成员函数getRecordDetails()总是返回一些固定的数据。

处理程序.js

const sinon = require("sinon");
const Database = require("../../lib/Database");
const database= new Database();

module.exports = {
  handler(event, context, callback) {
    event.Records.forEach(record=> {
       const recordDetails = database.getRecordDetails(record);
       // Do something with recordDetails
    });
  }
}
..

测试.js

const sinon = require("sinon");
const db= require("../../lib/Database");
const lamdbda = require("../../lib/lambda.js");

describe("Test suite", () => {
  it("invoke lambda",  done => {
    lambda.handler(data, {}, (err, data) => {
      sinon.stub(db, "getRecordDetails").withArgs(sinon.match.any).returns("{id: 1}");
      ...
    }
  }

}

database.js

class Database {
  constructor() {
    this.dynamdbClient = new AWS.DynamoDB.DocumentClient();
  }

  getRecordDetails(record) {
    const param = {
      TableName: ..
      Key: {
        uuid: record.uuid
        ...
     }
    }
    const dbRecord = await docClient.get(params).promise();
    return mapToRecordDetails(dbRecord); // new object mostly 1-1 mappings.
  }

}

但我得到:
TypeError:无法存根不存在的自己的属性getRecordDetails我做错了什么?

5uzkadbs

5uzkadbs1#

getRecordDetails方法是Database类的示例方法。请尝试sinon.stub(Database.prototype, 'getRecordDetails')
例如
handle.js

const Database = require('./database');
const database = new Database();

module.exports = {
  handler(event, context, callback) {
    event.Records.forEach((record) => {
      const recordDetails = database.getRecordDetails(record);
      console.log("🚀 ~ file: handler.js:8 ~ event.Records.forEach ~ recordDetails:", recordDetails)
    });
  },
};

database.js

const AWS = require('aws-sdk');

class Database {
  constructor() {
    this.dynamdbClient = new AWS.DynamoDB.DocumentClient();
  }

  async getRecordDetails(record) {
    const param = {
      TableName: 'a',
      Key: {
        uuid: record.uuid,
      },
    };
    return docClient.get(params).promise();
  }
}

module.exports = Database;

handler.test.js

const sinon = require('sinon');
const Database = require('./database');
const lamdbda = require('./handler.js');

describe('Test suite', () => {
  it('invoke lambda', () => {
    sinon.stub(Database.prototype, 'getRecordDetails').returns('{id: 1}');
    lamdbda.handler({ Records: [1] }, {}, (err, data) => {});
  });
});

试验结果:

Test suite
🚀 ~ file: handler.js:8 ~ event.Records.forEach ~ recordDetails: {id: 1}
    ✓ invoke lambda

  1 passing (4ms)

相关问题