bigblind
bigblind

Reputation: 12867

Mock entire es6 class except constructor in Jest?

If I have a class A, like this:

class A{
    constructor(foo){
        this.foo = foo;
    }

    doStuff(){
        //Code protected by an NDA, they'll nuke my house if I tell you what it does.
    }

    nukeHouse(){
        //The implementation of this is somewhat buggy...
    }
}

I'd like users of the class A to have access to this.foo, so I don't want to mock the constructor. All other methods should be mocked. I can probably manually say A.prototype.doStuff = jest.genMockFunction()ù, and do the same forA.prototype.nukeHouse`, but I'm hoping there's a way to do this, without having to update the mocking code every time I add a method to A.

Is there a way to do this?

Upvotes: 1

Views: 1172

Answers (1)

Felix Kling
Felix Kling

Reputation: 816424

I guess the generic solution would be to simply iterate over the prototype and create a mock function for each property:

var A = require.requireActual('./A');

Object.getOwnPropertyNames(A.prototype).forEach(function(prop) {
  A.prototype[prop] = jest.genMockFunction();
});

module.exports = A;

This may be more difficult if the class extends another class.

Upvotes: 2

Related Questions