我正在尝试为使用 aws-sdk
NPM 模块的应用程序编写一些测试覆盖率,该模块将事物推送到 SQS 队列,但我不确定如何正确地模拟事物。
这是我目前的测试:
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,所以请原谅我的无知
最佳答案
这就是我使用 sinonjs stub AWS-SDK 的方式
import AWS from 'aws-sdk'
import sinon from 'sinon'
let sinonSandbox
const beforeEach = (done) => {
sinonSandbox = sinon.sandbox.create()
done()
}
const afterEach = done => {
sinonSandbox.restore()
done()
}
lab.test('test name', (done) => {
sinonSandbox.stub(AWS, 'SQS')
.returns({
getQueueUrl: () => {
return {
QueueUrl: 'https://www.sample.com'
}
}
})
done()
})
基本上我控制来自主 SQS 的所有方法。希望这会对某人有所帮助
关于node.js - 带有 AWS-SDK 的 Node 中的 Sinon.Stub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26243647/