【发布时间】:2019-04-19 20:37:42
【问题描述】:
尝试为 /utility/sqsThing.js 中的以下模块编写单元测试。但是我很难模拟 sqs.sendMessage 方法。任何人都知道我应该怎么做。我正在使用 sinon 库和 mocha 来运行测试。
我正在尝试对utility/sqsThing.js 进行单元测试的函数:
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-1' });
const sqs = new AWS.SQS({ apiVersion: '2012-11-05' });
const outputQueURL = 'https:awsUrl';
const SQSOutputSender = (results) => {
const params = {
MessageBody: JSON.stringify(results),
QueueUrl: outputQueURL,
};
// Method that I want to mock
sqs.sendMessage(params, function (err, data) {
if (err) {
console.log('Error');
} else {
console.log('Success', data.MessageId);
}
});
};
我尝试在单元测试sqsThingTest.js 中模拟 sqs.sendMessage 方法:
const sqsOutputResultSender = require('../utility/sqsThing');
const AWS = require('aws-sdk');
const sqs = new AWS.SQS({ apiVersion: '2012-11-05' });
const mochaccino = require('mochaccino');
const { expect } = mochaccino;
const sinon = require('sinon');
describe('SQS thing test', function() {
beforeEach(function () {
sinon.stub(sqs, 'sendMessage').callsFake( function() { return 'test' });
});
afterEach(function () {
sqs.sendMessage.restore();
});
it('sqsOutputResultSender.SQSOutputSender', function() {
// Where the mock substitution should occur
const a = sqsOutputResultSender.SQSOutputSender('a');
expect(a).toEqual('test');
})
});
使用mocha tests/unit/sqsThingTest.js 运行这个单元测试但是我得到:
AssertionError: expected undefined to deeply equal 'test'。
info: Error AccessDenied: Access to the resource https://sqs.us-east-1.amazonaws.com/ is denied.。
看起来模拟没有取代 aws api 调用。有人知道我如何在测试中模拟 sqs.SendMessage 吗?
【问题讨论】:
-
试试 sinon.stub(sqs.prototype, 'sendMessage')
-
@JonathanNewton 尝试过
sinon.stub(sqs.prototype, 'sendMessage').callsFake( function() { return 'test' })。这给了我这个错误:Error: Trying to stub property 'sendMessage' of undefined
标签: javascript node.js unit-testing mocha.js sinon