When using jest.fn()
to add a mock you can usually access the .mock
property to access details such as calls, something similar to this:
test('not working', () => {
const foo = new Foo();
foo.addListener = jest.fn();
foo.func(); // will call addListener with a callback
const callback = foo.addListener.mock.calls[0][0];
expect(callback()).toEqual(1); // test the callback
});
When implementing the test in typescript instead of plain javascript I get the error:
error TS2339: Property 'mock' does not exist on type '(callback: () => number) => void'.
I can get rid of the error by casting to any
but surely there must be a better way:
const callback = (foo.addListener as any).mock.calls[0][0];
In this simple code the mock could be rewritten to store the argument using jest.fn(fn => { callback = fn; });
but the same error happens when using foo.addListener.mockClear()
which cannot be reworked the same way.
So how can I get rid of the error, preferably without losing type-safety?
question from:
https://stackoverflow.com/questions/52457575/jest-typescript-property-mock-does-not-exist-on-type 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…