'How to use mocha to stub tightly coupled dependencies

I have a class (Worker.js) that extends a base class which makes use of some AWS-SDK functionality. When writing tests for Worker.js, I need to stub out the AWS-SDK functionality, but I'm unsure how to write the stubs since the code is tightly coupled:

// base.js
const AWS = require('aws-sdk')
 
let S3 = new AWS.S3({
  apiVersion: '2006-03-01',
  region: 'eu-west-1'
})
 
class Base = {
    constructor() {}
 
    async init() {
        await this.getConfig()
    }
 
    async getConfig() {
        const data = await S3.getObject({})
        this.config = data;
    }
}
module.exports = Base
 
// worker.js
const Base = require('./base')
 
class Worker extends Base {
    constructor() {
        super()
    }
 
    async doWork() {
        await this.init()
    }
}
 
module.exports = Worker

At the moment, this kind of test fails.

const Worker = require('../../src/Worker.js')

describe('Worker', () => {
  describe('doWork', () => {
    it('should do some work when called', async () => {
      const worker = new Worker()
      try {
        await worker.doWork()
      } catch (err) {
        expect(err).to.be.undefined
      }
    })
  })
})

I've tried using rewire in my test like:

let S3 = sinon.stub();
S3.getObject = () => {
   return {
     promise: () => {
       return Promise.resolve(s3response);
     }
   };
};

Worker.__set__({
   S3: S3,
});

but it then claims it can't find S3, and then doing something like importing the Base, setting it there and rewiring the Worker with the Base class causes it to error with Base not being a constructor.

So how do you easily stub this out?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source