Sinon Spy 在使用构造函数初始化对象时不起作用'new'



我需要一个间谍来检查DynamoDb客户端(docClient(的'put'方法的参数。我从来没有遇到过间谍的问题,但在这种情况下,实例是由"new"构造函数创建的,我的实例(docClient(不会被存根——事实上,当它在dynamodb中被调用"put"方法存储参数时,当我检查间谍时,参数列表是空的。

articles/index.js

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = async function handler() {
await docClient.put({
TableName: 'Articles',
Item: {
title: 'Title Example',
body: 'Body Example'
},
}).promise();
}

test.js

const AWS = require('aws-sdk');
const mochaPlugin = require('serverless-mocha-plugin');
const sandbox = require('sinon').createSandbox();

const docClient = new AWS.DynamoDB.DocumentClient();
const { expect } = mochaPlugin.chai;
let wrapped = mochaPlugin.getWrapper('articles', '/src/functions/articles/index.js', 'handler');
describe('Articles Tests', function ArticlesTests() {
afterEach(() => {
sandbox.restore();
});
it('should store correctly a data', async () => {
let docClientSpy = sandbox.stub(docClient,'put');
await wrapped.run();
const articleData = docClientSpy.args;
expect(articleData.TableName).to.be.equal('Articles');
})
})

articleData是一个空数组。但当然不应该。

sandbox.stub(docClient,'put')在test.js中定义的docClient实例上存根一个方法。由于它与index.js中使用的实例不同,因此存根方法没有效果。

原型方法可以在类原型上被监视或嘲笑,但这是特定于类实现的。putDocumentClient的原型方法,所以这是允许的。否则,整个DocumentClient将被嘲笑,并且由于它是在index.js导入上实例化的,这将使测试变得复杂。

由于预计put()具有promise()方法,因此应模拟实现:

let promiseSpy = sandbox.stub().returns(Promise.resolve());
let docClientSpy = sandbox.stub(AWS.DynamoDB.DocumentClient.prototype, 'put').returns({ promise: promiseSpy });
...
expect(promiseSpy).to.have.been.called;

最新更新