Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to spyOn().and.callfake in Jestjs

I used to have spyOn().and.callFake in jasmine and it helps a lot in my tests, now I'm using Jest, I've found in the doc that jest.spyOn() exist but without the callFake.

My Question: How to spy on a method and call Fake with Jest and expect?

like image 457
JSK Avatar asked May 09 '17 20:05

JSK


People also ask

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.

How do I create a Spy 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 Jest fn ()?

The Jest library provides the jest. fn() function for creating a “mock” function. An optional implementation function may be passed to jest. fn() to define the mock function's behavior and return value. The mock function's behavior may be further specified using various methods provided to the mock function such as .

What is spyOn in Jasmine?

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result. This example shows how spyOn works, even if we are still mocking up our service.


1 Answers

jest.spyOn official documentation gives a great answer:

Note: By default, jest.spyOn also calls the spied method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use jest.spyOn(object, methodName).mockImplementation(() => customImplementation) or object[methodName] = jest.fn(() => customImplementation);

So in your case just pass a fake method to customImplementation.

like image 102
eddyP23 Avatar answered Sep 20 '22 19:09

eddyP23