3

I'm mocking an interface class:

const error = "Child must implement method";

class MyInterface
{
  normalFunction()
  {
    throw error;
  }

  async asyncFunction()
  {
    return new Promise(() => Promise.reject(error));
  }
}

class MyImplementation extends MyInterface
{
}

If any of the interface methods are called without an overridden implementation, the error gets thrown. However these errors will only appear at time of execution.

Is there a way to check that the functions were overridden at construction?

sookie
  • 2,437
  • 3
  • 29
  • 48
  • "at construction": you mean at construction of an instance of `MyImplementation`? – trincot May 03 '19 at 14:20
  • @trincot Yes, most likely within `MyInterface` constructor – sookie May 03 '19 at 14:25
  • You will have to implement something like a factory pattern to perform that check. I don't think there is something native to JS to do this. – sjahan May 03 '19 at 14:46
  • BTW: you can just `throw` the error in the `async` function: it will result in the rejection of the promise that is returned. – trincot May 03 '19 at 15:09
  • @trincot Yes. I did that to reinforce the "asynchronicity" of the function. I'm a little busy atm, but will take a look at your solution soon – sookie May 03 '19 at 15:13

2 Answers2

3

You could add some inspection in the constructor of MyInterface, like this:

class MyInterface {
    constructor() {
        const proto = Object.getPrototypeOf(this);
        const superProto = MyInterface.prototype;
        const missing = Object.getOwnPropertyNames(superProto).find(name =>
            typeof superProto[name] === "function" && !proto.hasOwnProperty(name)
        );
        if (missing) throw new TypeError(`${this.constructor.name} needs to implement ${missing}`);
    }

    normalFunction() {}

    async asyncFunction() {}
}

class MyImplementation extends MyInterface {}

// Trigger the error:
new MyImplementation();

Note that there are still ways to create an instance of MyImplementation without running a constructor:

Object.create(MyImplementation.prototype)
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Can't you use reflection in order to list all the function of a class?

For example here https://stackoverflow.com/a/31055217/10691359 give us a function which list all function of an object. Once you get all of them, you can see if you have or not an overridden function.

Pilpo
  • 1,236
  • 1
  • 7
  • 18