So I'm using a library called deride to be able to stub and force an error for testing purposes, which works nicely with frozen objects. However, I need to call a method on the wrapped object, but inside it calls another method and I need that method to be the stubbed call.
So I'm not expecting people to be familiar with deride, but the question is: Without modifying the original method, is it possible for the wrapped function greet
to call the wrapped salutation
function rather than the original?
Can this be achieved by setting the binding context?
describe('sample', function() {
function Person(name) {
function salutation() {
return 'hello';
}
function greet(otherPersonName) {
return [name, 'says', salutation(), 'to', otherPersonName].join(' ');
}
return Object.freeze({
salutation: salutation,
greet: greet
});
}
it.only('foobar', function() {
var bob = deride.wrap(new Person('bob'));
bob.setup.salutation.toReturn('mooooo');
var response = bob.greet('sally');
console.log(response);
assert.equal(response, 'bob says mooooo to sally');
});
});
Sorry but I can't see a way you can do this without violating the immutability of Person.
Deride plays nicely with Object.freeze as it wraps, not modifies the object, therefore the internal reference to salutation() will always be the frozen instantiation of the object rather than your stubbed, wrapped method.
Ultimately if you took the responsibility of salutation() out of this class and into a separate class which was injected, the code would become more testable as you could override the dependency prior to the Object.freeze