I have an object with two methods.
foo.publicMethod() will call foo.privateMethod() internally.
For example:
foo.prototype.publicMethod = function() {
return this.privateMethod()
.then(/* Do some other stuff */);
};
In order to test the public method in isolation I am stubbing the private method, by making it return an empty promise. For some reason, if I assign
foo.privateMethod = () => Promise.resolve();
everything works out fine, however doing
foo.privateMethod = Promise.resolve;
produces an error message: TypeError: object is not a constructor
I can't see how these two lines of code would produce a different result. Yes, one is technically wrapping Promise.resolve once, but I don't see how this should affect the end result. Any ideas what the difference might be?
The two are not exactly the same. In the working version the context of the resolve call is the Promise object. In the second version, the context is whatever context privateMethod is called with, which would be foo when you call it as foo.privateMethod().
To make sure you have the context set correctly with the second syntax, use bind:
foo.privateMethod = Promise.resolve.bind(Promise);
function Foo() {}
Foo.prototype.publicMethod = function() {
return this.privateMethod();
};
var foo = new Foo();
foo.privateMethod = Promise.resolve.bind(Promise);
// Test it
foo.publicMethod().then ( _ => console.log('done'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With