Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace jest.spyOn().and.returnValue()?

While upgrading Angular (via Nx/NRWL) from 11 to 12, tests started to fail due to: Property 'and' does not exist on type 'SpyInstance<{ afterClosed: () => Observable<{ snoozeDate: Moment; snoozeNote: string; }>; }, []>'.

There are ~30 some tests that use the .and.returnValue.

Examples:

  • jest.spyOn(mockMatDialog, 'open').and.returnValue({ afterClosed: () => of(true)});,
  • jest.spyOn(component.randomHelperService, 'myHelper').and.returnValue('12354');

What is the best way to replace this "returnValue" behavior? FYI, I have this set too, testRunner: 'jest-jasmine2', in order to make other syntax work after the upgrade.

like image 237
mrshickadance Avatar asked Jul 13 '26 13:07

mrshickadance


1 Answers

You can change the testRunner back and use mockReturnValue instead of and.returnValue. See

jest.spyOn(mockMatDialog, 'open').mockReturnValue({ afterClosed: () => of(true)});
jest.spyOn(component.randomHelperService, 'myHelper').mockReturnValue('12354');

I'm not sure when it was changed but I had to deal with the same issue. This was the solution

like image 54
mat.hudak Avatar answered Jul 15 '26 03:07

mat.hudak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!