我有一个问题是存根调用DynamoDB进行API测试。我使用无服务器的mocha并希望从端到端的角度测试我的API。项目结构并不简单,但在API文件本身内部,我对不同的类文件进行单独调用以实际使用DynamoDB函数。我们假设它是一个库。 因此,我不能使用aws-sdk-mock,因为需求" AWS服务需要在被测试的函数内初始化,以便模拟SDK方法"不是我的情况。 我如何测试我的API和存根调用DynamoDB? 现在测试实际上正在工作,但它实际上是对我想要避免的数据库的调用:
const isStub = true;
const mochaPlugin = require('serverless-mocha-plugin');
const chaiExclude = require('chai-exclude');
const sinon = require('sinon');
mochaPlugin.chai.use(chaiExclude);
const expect = mochaPlugin.chai.expect;
const assert = mochaPlugin.chai.assert;
let createHandler = mochaPlugin.getWrapper('postStory', '/../../functions/create/create.js', 'handler');
const { constants } = require('core/index');
const localConstants = require('../utils/constants');
const AWS = require('aws-sdk');
const AWSMock = require('aws-sdk-mock');
describe('create', () => {
let dynamoSpy = sinon.spy();
before((done) => {
if (isStub) {
AWSMock.mock('DynamoDB.DocumentClient', 'put', dynamoSpy);
}
done();
});
after((done) => {
if (isStub) {
assert.isTrue(dynamoSpy.calledOnce, 'should make at least one call to DynamoDB via AWS SDK');
AWSMock.restore('DynamoDB.DocumentClient', 'put');
sinon.reset();
}
done();
});
it('should pass object with correct values to save', function () {
return createHandler.run(require('../events/create/create.json')).then((response) => {
console.log(response);
expect(response.statusCode).to.equal(201);
});
});
答案 0 :(得分:0)
我遇到了同样的问题,我通过使用sinon解决了该问题,请查看如何对Dynamo函数进行存根,然后测试所需的内容:
import {expect} from 'chai';
import * as AWS from 'aws-sdk';
import * as sinon from 'sinon';
let result = {
// your result
}
let sinonSandbox;
beforeEach((done) => {
sinonSandbox = sinon.createSandbox();
done();
})
afterEach((done) => {
sinonSandbox.restore()
done();
})
it('your test', async () => {
sinonSandbox.stub(AWS.DynamoDB.DocumentClient.prototype, 'put').returns({
promise: function () {
return Promise.resolve(result);
}
});
return createHandler.run(require('../events/create/create.json')).then((response) => {
console.log(response);
expect(response.statusCode).to.equal(201);
});
});
在此示例中,我对promise实现进行了存根,我相信您可以通过这样的回调对put进行存根:
sinonSandbox.stub(AWS.DynamoDB.DocumentClient.prototype, 'put').returns((params,callback) => {
callback(null,result);
});