Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest spyOn not working with typescript: "Property 'mockRestore' is missing in type 'Spy'"

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.

like image 504
jjbskir Avatar asked Dec 31 '18 15:12

jjbskir


People also ask

How do you use spyOn function in jest?

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.

What is the difference between jest FN and jest spyOn?

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.

What is spyOn jest?

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.


1 Answers

Short Answer

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');

Further Explanation

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.

  • The spyOn that returns a jest.SpyInstance is inside the jest namespace.
  • The 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.

like image 110
Shaun Luttin Avatar answered Nov 15 '22 07:11

Shaun Luttin