Ask Sawal

Discussion Forum
Notification Icon1
Write Answer Icon
Add Question Icon

How to spy on function?

4 Answer(s) Available
Answer # 1 #

A spy will only exist in the describe or it block that it is defined. For this reason, when working on these tests, we will be using describe blocks per function that is being tested.

Let’s take a look at the Jasmine Spies I use most often when writing unit tests.

The first spy we will look at is the and.callThrough spy. This spy will track calls to the function it is spying on, but it will also pass through to the function and allow it to run. This means that when we use this spy, the function being spied on will still do what it is written to do, but we can track the calls to it. Look at the following example.

Now let’s install an and.callThrough spy for the addThing function of thing.

For all the spies in this article, we will be using spyOn(obj, methodName) to install our spies. For the spy on addThing we are saying that we want to install a spy on thing and that we are replacing the method with the method name addThing.

Now that the and.callThrough spy is installed, let’s look at what we can do with it by looking at some expect statements.

If all we want to know is that our function that is being spied on has been called, toHaveBeenCalled is what we are looking for. The following expect just tests that our spy has been called, not caring about parameters, how many times it may have been called, or anything else.

When thing.addThing is called, the spy will register that it was called and this can now be used by the expect. The function will still do what it was going to do, so if we displayed the contents of stuff it would be .

To test that a function has been called the appropriate amount of times, use the toHaveBeenCalledTimes matcher.

Because the spy is still and.callThrough, thing1 and thing2 will be added to stuff.

Now let’s look at the and.callFake spy. This spy will track all calls to the defined function, but with this, we can pass in a new function that will be called in place of the original.

and.callFake shines in its ability to allow you to define what a function call does depending on the describe or it block it is in. This spy is also very handy when a quick mock of a function is needed.

The and.returnValue spy is probably the one I have used most often. Just like the other spies, it will track the calls to the function, but instead of calling the function, you can specify a value to return. This can make setting up your test scenarios much easier.

The last Jasmine Spy we will look at is the and.throwError spy. With this spy, every call will throw an error with the specified value.

Using the and.throwError spy gives us an easy and clean way to have our tests throw an error, so we can make sure to test that our error functionality is also working as intended.

Unit testing is an important part of the development process. It gives us the ability to know that our code is working as intended and can also let us know if we may have broken something that we didn’t even think of.

With the help of Jasmine Spies, we can make our test setup easier, and we can give ourselves more options for what we can test against. Hopefully, this will give you a good starting point for all your Jasmine spying needs!

[3]
Edit
Query
Report
Asgher rgzujb
LIQUEFACTION PLANT OPERATOR
Answer # 2 #

Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output. You can create a mock function with jest.fn(). If no implementation is given, the mock function will return undefined when invoked.

Returns the mock name string set by calling .mockName().

An array containing the call arguments of all calls that have been made to this mock function. Each item in the array is an array of arguments that were passed during the call.

For example: A mock function f that has been called twice, with the arguments f('arg1', 'arg2'), and then with the arguments f('arg3', 'arg4'), would have a mock.calls array that looks like this:

An array containing the results of all calls that have been made to this mock function. Each entry in this array is an object containing a type property, and a value property. type will be one of the following:

The value property contains the value that was thrown or returned. value is undefined when type === 'incomplete'.

For example: A mock function f that has been called three times, returning 'result1', throwing an error, and then returning 'result2', would have a mock.results array that looks like this:

An array that contains all the object instances that have been instantiated from this mock function using new.

For example: A mock function that has been instantiated twice would have the following mock.instances array:

An array that contains the contexts for all calls of the mock function.

A context is the this value that a function receives when called. The context can be set using Function.prototype.bind, Function.prototype.call or Function.prototype.apply.

For example:

An array containing the call arguments of the last call that was made to this mock function. If the function was not called, it will return undefined.

For example: A mock function f that has been called twice, with the arguments f('arg1', 'arg2'), and then with the arguments f('arg3', 'arg4'), would have a mock.lastCall array that looks like this:

Clears all information stored in the mockFn.mock.calls, mockFn.mock.instances, mockFn.mock.contexts and mockFn.mock.results arrays. Often this is useful when you want to clean up a mocks usage data between two assertions.

The clearMocks configuration option is available to clear mocks automatically before each tests.

Does everything that mockFn.mockClear() does, and also removes any mocked return values or implementations.

This is useful when you want to completely reset a mock back to its initial state.

The resetMocks configuration option is available to reset mocks automatically before each test.

Does everything that mockFn.mockReset() does, and also restores the original (non-mocked) implementation.

This is useful when you want to mock functions in certain test cases and restore the original implementation in others.

The restoreMocks configuration option is available to restore mocks automatically before each test.

Accepts a function that should be used as the implementation of the mock. The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called.

.mockImplementation() can also be used to mock class constructors:

Accepts a function that will be used as an implementation of the mock for one call to the mocked function. Can be chained so that multiple function calls produce different results.

When the mocked function runs out of implementations defined with .mockImplementationOnce(), it will execute the default implementation set with jest.fn(() => defaultValue) or .mockImplementation(() => defaultValue) if they were called:

Accepts a string to use in test result output in place of 'jest.fn()' to indicate which mock function is being referenced.

For example:

Will result in this error:

Shorthand for:

Shorthand for:

Accepts a value that will be returned whenever the mock function is called.

Shorthand for:

Accepts a value that will be returned for one call to the mock function. Can be chained so that successive calls to the mock function return different values. When there are no more mockReturnValueOnce values to use, calls will return a value specified by mockReturnValue.

Shorthand for:

Useful to mock async functions in async tests:

Shorthand for:

Useful to resolve different values over multiple async calls:

Shorthand for:

Useful to create async mock functions that will always reject:

Shorthand for:

Useful together with .mockResolvedValueOnce() or to reject with different exceptions over multiple async calls:

Accepts a function which should be temporarily used as the implementation of the mock while the callback is being executed.

mockFn.withImplementation can be used regardless of whether or not the callback is asynchronous (returns a thenable). If the callback is asynchronous a promise will be returned. Awaiting the promise will await the callback and reset the implementation.

Changes the value of already replaced property. This is useful when you want to replace property and then adjust the value in specific tests. As an alternative, you can call jest.replaceProperty() multiple times on same property.

Restores object's property to the original value.

Beware that replacedProperty.restore() only works when the property value was replaced with jest.replaceProperty().

The restoreMocks configuration option is available to restore replaced properties automatically before each test.

Correct mock typings will be inferred if implementation is passed to jest.fn(). There are many use cases where the implementation is omitted. To ensure type safety you may pass a generic type argument (also see the examples above for more reference):

Constructs the type of a mock function, e.g. the return type of jest.fn(). It can be useful if you have to defined a recursive mock function:

The jest.Mocked utility type returns the Source type wrapped with type definitions of Jest mock function.

Types of classes, functions or objects can be passed as type argument to jest.Mocked. If you prefer to constrain the input type, use: jest.MockedClass, jest.MockedFunction or jest.MockedObject.

The jest.Replaced utility type returns the Source type wrapped with type definitions of Jest replaced property.

The mocked() helper method wraps types of the source object and its deep nested members with type definitions of Jest mock function. You can pass {shallow: true} as the options argument to disable the deeply mocked behavior.

Returns the source object.

Constructs the type of a spied class or function (i.e. the return type of jest.spyOn()).

[2]
Edit
Query
Report
wbtv Khan
COVERING MACHINE OPERATOR
Answer # 3 #

If you write unit tests, then you likely use a testing framework and might have come across spies. If you don’t write unit tests, please take a quick pause and promise yourself to always write tests.

Spies allow you to monitor a function; they expose options to track invocation counts, arguments and return values. This enables you to write tests to verify function behaviour.

They can even help you mock out unneeded functions. For example, dummy spies can be used to swap out AJAX calls with preset promise values.

The code below shows how to spy on the bar method of object foo.

That was pretty cool right. So how difficult can it be to write a spy and what happens under the hood?  It turns out implementing a spy is very easy in JavaScript. So let’s write ours!

The goal of the spy is to intercept calls to a specified function. A possible approach is to replace the original function with another function that stores necessary information and then invokes the original method. Partial application makes this quite easy…

The spy method takes an object and a method to be spied upon. Next, it creates an object containing the call count and an array tracking invocation arguments.

It swaps out the original call with a new function that always updates the information object whenever the original method is invoked.

The Object.freeze call ‘freezes’ the spy object and prevents any modifications of values. This is necessary to prevent arbitrary changes of the spied values.

The toy sample is brittle (yes I know it). Can you spot the issues? Here are some:

These can (and should) be fixed but again, that would make this post very complicated. The goal was to show a simple toy implementation.

How do you ‘unregister’  spies without losing the original method? Hint: store it in some closure and replace once you expose an unregister call.

[2]
Edit
Query
Report
ybbvltx Creativity
SUPERVISOR NATURAL GAS FIELD PROCESSING
Answer # 4 #

Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output. You can create a mock function with jest.fn(). If no implementation is given, the mock function will return undefined when invoked.

Returns the mock name string set by calling .mockName().

An array containing the call arguments of all calls that have been made to this mock function. Each item in the array is an array of arguments that were passed during the call.

For example: A mock function f that has been called twice, with the arguments f('arg1', 'arg2'), and then with the arguments f('arg3', 'arg4'), would have a mock.calls array that looks like this:

An array containing the results of all calls that have been made to this mock function. Each entry in this array is an object containing a type property, and a value property. type will be one of the following:

The value property contains the value that was thrown or returned. value is undefined when type === 'incomplete'.

For example: A mock function f that has been called three times, returning 'result1', throwing an error, and then returning 'result2', would have a mock.results array that looks like this:

An array that contains all the object instances that have been instantiated from this mock function using new.

For example: A mock function that has been instantiated twice would have the following mock.instances array:

An array that contains the contexts for all calls of the mock function.

A context is the this value that a function receives when called. The context can be set using Function.prototype.bind, Function.prototype.call or Function.prototype.apply.

For example:

An array containing the call arguments of the last call that was made to this mock function. If the function was not called, it will return undefined.

For example: A mock function f that has been called twice, with the arguments f('arg1', 'arg2'), and then with the arguments f('arg3', 'arg4'), would have a mock.lastCall array that looks like this:

Clears all information stored in the mockFn.mock.calls, mockFn.mock.instances, mockFn.mock.contexts and mockFn.mock.results arrays. Often this is useful when you want to clean up a mocks usage data between two assertions.

The clearMocks configuration option is available to clear mocks automatically before each tests.

Does everything that mockFn.mockClear() does, and also removes any mocked return values or implementations.

This is useful when you want to completely reset a mock back to its initial state.

The resetMocks configuration option is available to reset mocks automatically before each test.

Does everything that mockFn.mockReset() does, and also restores the original (non-mocked) implementation.

This is useful when you want to mock functions in certain test cases and restore the original implementation in others.

The restoreMocks configuration option is available to restore mocks automatically before each test.

Accepts a function that should be used as the implementation of the mock. The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called.

.mockImplementation() can also be used to mock class constructors:

Accepts a function that will be used as an implementation of the mock for one call to the mocked function. Can be chained so that multiple function calls produce different results.

When the mocked function runs out of implementations defined with .mockImplementationOnce(), it will execute the default implementation set with jest.fn(() => defaultValue) or .mockImplementation(() => defaultValue) if they were called:

Accepts a string to use in test result output in place of 'jest.fn()' to indicate which mock function is being referenced.

For example:

Will result in this error:

Shorthand for:

Shorthand for:

Accepts a value that will be returned whenever the mock function is called.

Shorthand for:

Accepts a value that will be returned for one call to the mock function. Can be chained so that successive calls to the mock function return different values. When there are no more mockReturnValueOnce values to use, calls will return a value specified by mockReturnValue.

Shorthand for:

Useful to mock async functions in async tests:

Shorthand for:

Useful to resolve different values over multiple async calls:

Shorthand for:

Useful to create async mock functions that will always reject:

Shorthand for:

Useful together with .mockResolvedValueOnce() or to reject with different exceptions over multiple async calls:

Accepts a function which should be temporarily used as the implementation of the mock while the callback is being executed.

mockFn.withImplementation can be used regardless of whether or not the callback is asynchronous (returns a thenable). If the callback is asynchronous a promise will be returned. Awaiting the promise will await the callback and reset the implementation.

Changes the value of already replaced property. This is useful when you want to replace property and then adjust the value in specific tests. As an alternative, you can call jest.replaceProperty() multiple times on same property.

Restores object's property to the original value.

Beware that replacedProperty.restore() only works when the property value was replaced with jest.replaceProperty().

The restoreMocks configuration option is available to restore replaced properties automatically before each test.

Correct mock typings will be inferred if implementation is passed to jest.fn(). There are many use cases where the implementation is omitted. To ensure type safety you may pass a generic type argument (also see the examples above for more reference):

Constructs the type of a mock function, e.g. the return type of jest.fn(). It can be useful if you have to defined a recursive mock function:

The jest.Mocked utility type returns the Source type wrapped with type definitions of Jest mock function.

Types of classes, functions or objects can be passed as type argument to jest.Mocked. If you prefer to constrain the input type, use: jest.MockedClass, jest.MockedFunction or jest.MockedObject.

The jest.Replaced utility type returns the Source type wrapped with type definitions of Jest replaced property.

The mocked() helper method wraps types of the source object and its deep nested members with type definitions of Jest mock function. You can pass {shallow: true} as the options argument to disable the deeply mocked behavior.

Returns the source object.

Constructs the type of a spied class or function (i.e. the return type of jest.spyOn()).

Types of a class or function can be passed as type argument to jest.Spied. If you prefer to constrain the input type, use: jest.SpiedClass or jest.SpiedFunction.

[1]
Edit
Query
Report
nhfbr Esguerra
BENEFITS CLERK II