title: How to mock a function in another function nodejs
body: <p>Trying to write a unittest for the below module in /utility/sqsThing.js. However I'm having diffuculty mocking the <code>sqs.sendMessage</code> method. Anyone know how I should go about this. I'm using the sinon library, and mocha for running the tests.</p>
  
  <p>The function that I'm trying to unittest <code>utility/sqsThing.js</code>:</p>
  
  <pre><code>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) =&gt; {
    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);
      }
    });
  };
  </code></pre>
  
  <p>My attempt at mocking the sqs.sendMessage method in a unittest <code>sqsThingTest.js</code>:</p>
  
  <pre><code>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');
    })
  });
  </code></pre>
  
  <p>Running this unittest with <code>mocha tests/unit/sqsThingTest.js</code> however I get:
  <code>AssertionError: expected undefined to deeply equal 'test'</code>.
  <code>info: Error AccessDenied: Access to the resource https://sqs.us-east-1.amazonaws.com/ is denied.</code>. </p>
  
  <p>It looks like the mock did not replace the aws api call. Anyone know how I can mock <code>sqs.SendMessage</code> in my test?</p>