How to replace jest.spyOn().and.returnValue()?
Asked Answered
P

1

7

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.

Puto answered 16/6, 2022 at 15:46 Comment(0)
A
18

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

Achievement answered 16/6, 2022 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.