2

我有一些问题存根这种依赖关系。我知道有一个 aws-sdk-mock 模块,但我的目标是用 sinon 和 chai 存根它。这是mi代码,

测试代码

const chai = require('chai');
const sinon = require('sinon');
const chaiHttp = require('chai-http');
const app= require('./app');
chai.use(chaiHttp);

const queryMock =sinon.stub();

const dynamoMock = {
 DocumentClient:sinon.fake.returns({
    query:queryMock
 })
}


let awsDynamoMock;


describe.only('Integration test for activation',()=>{
    beforeEach(() => {
        awsDynamoMock = sinon.stub(require('aws-sdk'),'DynamoDB');   
        awsDynamoMock.returns(dynamoMock);
      })
    afterEach(() => {
        awsDynamoMock.restore();     
      })

    it('Request /endpoint returns HTTP 200 with {} when user exist and all task are done',(done)=>{
        const params = {
            TableName:'table',
            KeyConditionExpression: `client_id= :i`,
            ExpressionAttributeValues: {
              ':i': '23424234'
            },
            ConsistentRead:true
          };

          const userWithNoPendingsMock = {
            Items: [
              {
                client_id: "23424234",
              },
            ],
            Count: 1,
            ScannedCount: 1,
          }

        queryMock.withArgs(params).returns({
            promise:() =>sinon.fake.resolves(userWithNoPendingsMock)
           })


        chai
        .request(app)
        .post("/endpoint")
        .end( (err, res) => {
            chai.expect(res.status).to.be.eql(200);
            chai.expect(res.body).to.eql({});
             done();
        });

    });

})

连接到 dynamoDB 到存根

const AWS  = require('aws-sdk');
AWS.config.update({region:'REGION'});

let docClient = false;
const getDynamoSingleton = async () => {

  if (docClient) return docClient;

  docClient = new AWS.DynamoDB.DocumentClient();

  console.log(docClient)
  return docClient
}


module.exports = getDynamoSingleton 

使用 DynamoDB 示例

const getElementById = async (TableName,key,id)=>{

  const docClient = await getDynamoSingleton();

  //Make query params.
  const params = {
    TableName,
    KeyConditionExpression: `${key} = :i`,
    ExpressionAttributeValues: {
      ':i': id
    },
    ConsistentRead:true
  };



  //Run query as promise.
  return docClient.query(params).promise();

}

我真的坚持这个问题,所以任何帮助都会很有用。我知道问题与 de documentclient 有关

谢谢您的帮助

4

0 回答 0