Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

jestjs - jest typescript property mock does not exist on type

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For anyone getting here, a bit better than casting to any might be casting as jest.Mock

const callback = (foo.addListener as jest.Mock).mock.calls[0][0];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...