使用AWS-SDK在节点中的Sinon.Stub [英] Sinon.Stub in Node with AWS-SDK
问题描述
我正在尝试为使用aws-sdk
NPM模块将应用程序推入SQS队列的应用程序编写一些测试范围,但是我不确定如何正确模拟事物.
I am trying to write some test coverage for an app that uses the aws-sdk
NPM module that pushes things up to a SQS queue, but I am unsure how to mock things correctly.
到目前为止,这是我的测试:
Here is my test so far:
var request = require('superagent'),
expect = require('chai').expect,
assert = require('chai').assert,
sinon = require('sinon'),
AWS = require('aws-sdk'),
app = require("../../../../app");
describe("Activities", function () {
describe("POST /activities", function () {
beforeEach(function(done) {
sinon.stub(AWS.SQS.prototype, 'sendMessage');
done();
});
afterEach(function(done) {
AWS.SQS.prototype.sendMessage.restore();
done();
});
it("should call SQS successfully", function (done) {
var body = {
"custom_activity_node_id" : "1562",
"campaign_id" : "318"
};
reqest
.post('/v1/user/123/custom_activity')
.send(body)
.set('Content-Type', 'application/json')
.end(function(err, res) {
expect(res.status).to.equal(200)
assert(AWS.SQS.sendMessage.calledOnce);
assert(AWS.SQS.sendMessage.calledWith(body));
});
});
});
});
我看到的错误是:
1) Activities POST /activities "before each" hook:
TypeError: Attempted to wrap undefined property sendMessage as function
2) Activities POST /activities "after each" hook:
TypeError: Cannot call method 'restore' of undefined
关于sinon.stub
或JavaScript中的模拟对象,我有点 newb ,所以请原谅我的无知
I am a bit of a newb when it comes to sinon.stub
or mocking objects in JavaScript, so please excuse my ignorance
推荐答案
我们创建了一个 aws-sdk-mock npm模块,该模块模拟了所有AWS开发工具包服务和方法. https://github.com/dwyl/aws-sdk-mock
We have created an aws-sdk-mock npm module which mocks out all the AWS SDK services and methods. https://github.com/dwyl/aws-sdk-mock
它真的很容易使用.只需使用服务,方法和存根函数调用AWS.mock.
It's really easy to use. Just call AWS.mock with the service, method and a stub function.
AWS.mock('SQS', 'sendMessage', function(params, callback) {
callback(null, 'success');
});
然后通过调用以下方法恢复测试后的方法:
Then restore the methods after your tests by calling:
AWS.restore('SQS', 'sendMessage');
这篇关于使用AWS-SDK在节点中的Sinon.Stub的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!