Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting a not a constructor error when trying to stub an external class dependency #382

Closed
mattallenuk opened this issue Sep 10, 2018 · 3 comments

Comments

@mattallenuk
Copy link

mattallenuk commented Sep 10, 2018

Description

I'm trying to stub a dependency of the module I'm testing.

Issue

I'm new to using TestDouble so this is likely just my ignorance. I am trying, unsuccessfully so far, to stub a dependency of a module under test. The dependency is a module containing a class declared using module.exports = class clsName style. I can get a stubbed version but in my module when new clsName is executed it comes back with an error saying clsName is not a constructor.

I'm actually using Typescript but the code below is a contrived example of what I'm trying to do in plain Javascript. Is there anything obvious that I am doing wrong? Can I do what I'm attempting to do?

Environment

node 10.5.0
npm 6.3.0
testdouble 3.8.1
mocha 5.2.0

Code-fenced Examples

dep.js

module.exports = class DependencyA {
    constructor(options) {
        this.options = options;
    }
    doSomething(){
        return 'DidSomething';
    }
}

undertest.js

const DependencyA = require('./dep');
export class UnderTest {
   constructor() {
       this.depA = new DependencyA({anOption: 12});
   }
   doIt() {
       return this.depA.doSomething();
   }
}

test.js

const td = require('testdouble');
describe('UnderTest', () => {
    let UnderTest = null;
    beforeEach(() => {
        const DependencyA = td.replace('./dep');
        td.when(new DependencyA(td.matchers.anything())).thenReturn({});
        td.when(DependencyA.prototype.doSomething()).thenReturn('I did it!');
        UnderTest = require('./undertest').UnderTest;
    });

    afterEach(() => {
        UnderTest = null;
        td.reset();
    });
    
    it('Can Be Created', () => {
       const underTest = new UnderTest();
    });
});
@mattallenuk
Copy link
Author

Have managed to sort this out. Was not including the Dep.js file correctly in my Typescript code.

@searls
Copy link
Member

searls commented Sep 14, 2018

Sorry that I took so long to respond to you that you had to solve this entirely alone. I'll try to be more responsive!

@mattallenuk
Copy link
Author

Not a problem at all! Thanks @searls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants