I am trying to test that a function I’ve bind
ed is stubbed, but when I expect(myStub).toHaveBeenCalled();
I get this error message:
Error: <toHaveBeenCalled> : Expected a spy, but got Function.
Usage: expect(<spyObj>).toHaveBeenCalled()
I found this Sinon GitHub issue trying to achieve the same thing. It includes an answer that used to work:
export default class A {
makeRequest() {
return new Promise(this._resolve.bind(this));
}
_resolve(resolve, reject) {
// ...
}
}
// ...
test('A#makeRequest', sinon.test(function (t) {
var promiseConstructorStub = this.stub(window, 'Promise');
var a = new A();
sinon.stub(a._resolve, 'bind', () => a._resolve); // ERROR: no longer exists
a.makeRequest();
t.ok(promiseConstructorStub.firstCall.calledWith(a._resolve), 'cb passed'); // should work
t.end();
}));
As the comment says, this sinon.stub(a._resolve, 'bind', () => a._resolve);
function signature no longer exists.
Here’s my code which fails to compile for that reason:
beforeEach(() => {
myStub = sinon.stub(printError, 'bind').returns(myStub);
});
The 'bind'
has a compile time error that says:
Argument of type '"bind"' is not assignable to parameter of type 'keyof SinonStub<any[], any>'.
Here’s an excerpt of my production code:
export const addToDocument = (
d: Document,
printOnErrorOptions?: PrettyStringOptions
): void => {
d.toPrettyString = toPrettyString;
if (printOnErrorOptions !== undefined) {
d.printError = printError.bind(d, printOnErrorOptions);
} else {
d.printError = () => {}; /* noop */
}
};
// ...
export function printError(
this: Document,
printOnErrorOptions: PrettyStringOptions
): void {
logger.error(this.toPrettyString(printOnErrorOptions));
}
Here’s my question: how do you rewrite the example to work in modern Sinon code?