When using spyOn with jest and typescript I am getting this type error:
Type 'Spy' is not assignable to type 'SpyInstance<{}>'. Property 'mockRestore' is missing in type 'Spy'.
Here is a code example that causes it:
class A {
foo = () => this.bar() + 1;
bar = () => 1;
}
test('should pass', () => {
const a = new A();
let barSpy: jest.SpyInstance;
barSpy = spyOn(a, 'bar');
a.foo();
expect(barSpy).toHaveBeenCalled();
});
When I run this example the test passes, but the typescript complier fails.
To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.
jest. fn() is a method to create a stub, it allowing you to track calls, define return values etc... jest. spyOn() came from jasmine, it allow you to convert an existing method on an object into a spy, that also allows you to track calls and re-define the original method implementation.
Jest's spyOn method is used to spy on a method call on an object. It is also very beneficial in cases where the Jest mock module or mock function might not be the best tool for the job on hand. While writing unit tests you only test one particular unit of code, generally a function.
The global spyOn(...)
function returns a jasmine.Spy
not a jest.SpyInstance
. The reason for this, as far as I can tell, is to ease migration from Jasmine to Jest.
Here are two options:
let barSpy: jest.SpyInstance;
barSpy = jest.spyOn(a, 'bar'); // <--- explicitly use jest.spyOn
// or
let barSpy: jasmine.Spy; // <--- use jasmine.Spy as your type
barSpy = spyOn(a, 'bar');
The node_modules\@types\jest\index.d.ts
file has the Jest type definitions. By looking at them, we can see the two implementations of spyOn
.
spyOn
that returns a jest.SpyInstance
is inside the jest
namespace. spyOn
that returns a jasmine.Spy
is in the global namespace. Unless you're in the process of migrating from Jasmine to Jest, I would use the jest.spyOn
function instead of the global one.
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