Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values.
All mock functions have this special .mock property, which is where data about how the function has been called and what the function returned is kept. The .mock property also tracks the value of this for each call, so it is possible to inspect this as well:
Mock functions are also very effective in code that uses a functional continuation-passing style. Code written in this style helps avoid the need for complicated stubs that recreate the behavior of the real component they're standing in for, in favor of injecting values directly into the test right before they're used.
Most real-world examples actually involve getting ahold of a mock function on a dependent component and configuring that, but the technique is the same. In these cases, try to avoid the temptation to implement logic inside of any function that's not directly being tested.
Once we mock the module we can provide a mockResolvedValue for .get that returns the data we want our test to assert against. In effect, we are saying that we want axios.get('/users.json') to return a fake response.
Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with jest.fn or the mockImplementationOnce method on mock functions.
For cases where we have methods that are typically chained (and thus always need to return this), we have a sugary API to simplify this in the form of a .mockReturnThis() function that also sits on all mocks:
You can optionally provide a name for your mock functions, which will be displayed instead of 'jest.fn()' in the test error output. Use .mockName() if you want to be able to quickly identify the mock function reporting an error in your test output.
unittest.mock provides a core Mock class removing the need tocreate a host of stubs throughout your test suite. After performing anaction, you can make assertions about which methods / attributes were usedand arguments they were called with. You can also specify return values andset needed attributes in the normal way.
Additionally, mock provides a patch() decorator that handles patchingmodule and class level attributes within the scope of a test, along withsentinel for creating unique objects. See the quick guide forsome examples of how to use Mock, MagicMock andpatch().
Mock and MagicMock objects create all attributes andmethods as you access them and store details of how they have been used. Youcan configure them, to specify return values or limit what attributes areavailable, and then make assertions about how they have been used:
The patch() decorator / context manager makes it easy to mock classes orobjects in a module under test. The object you specify will be replaced with amock (or other object) during the test and restored when the test ends:
When you nest patch decorators the mocks are passed in to the decoratedfunction in the same order they applied (the normal Python order thatdecorators are applied). This means from the bottom up, so in the exampleabove the mock for module.ClassName1 is passed in first.
Mock allows you to assign functions (or other Mock instances) to magic methodsand they will be called appropriately. The MagicMock class is just a Mockvariant that has all of the magic methods pre-created for you (well, all theuseful ones anyway).
For ensuring that the mock objects in your tests have the same api as theobjects they are replacing, you can use auto-speccing.Auto-speccing can be done through the autospec argument to patch, or thecreate_autospec() function. Auto-speccing creates mock objects thathave the same attributes and methods as the objects they are replacing, andany functions and methods (including constructors) have the same callsignature as the real object.
Mock is a flexible mock object intended to replace the use of stubs andtest doubles throughout your code. Mocks are callable and create attributes asnew mocks when you access them [1]. Accessing the same attribute will alwaysreturn the same mock. Mocks record how you use them, allowing you to makeassertions about what your code has done to them.
The patch() decorators makes it easy to temporarily replace classesin a particular module with a Mock object. By default patch() will createa MagicMock for you. You can specify an alternative class of Mock usingthe new_callable argument to patch().
spec: This can be either a list of strings or an existing object (aclass or instance) that acts as the specification for the mock object. Ifyou pass in an object then a list of strings is formed by calling dir onthe object (excluding unsupported magic attributes and methods).Accessing any attribute not in this list will raise an AttributeError.
side_effect: A function to be called whenever the Mock is called. Seethe side_effect attribute. Useful for raising exceptions ordynamically changing return values. The function is called with the samearguments as the mock, and unless it returns DEFAULT, the returnvalue of this function is used as the return value.
Create the child mocks for attributes and return value.By default child mocks will be the same type as the parent.Subclasses of Mock may want to override this to customize the waychild mocks are made.
If you pass in a function it will be called with same arguments as themock and unless the function returns the DEFAULT singleton thecall to the mock will then return whatever the function returns. If thefunction returns DEFAULT then the mock will return its normalvalue (from the return_value).
If you pass in an iterable, it is used to retrieve an iterator whichmust yield a value on every call. This value can either be an exceptioninstance to be raised, or a value to be returned from the call to themock (DEFAULT handling is identical to the function case).
call_args, along with members of the lists call_args_list,method_calls and mock_calls are call objects.These are tuples, so they can be unpacked to get at the individualarguments and make more complex assertions. Seecalls as tuples.
This is a list of all the calls made to the mock object in sequence(so the length of the list is the number of times it has beencalled). Before any calls have been made it is an empty list. Thecall object can be used for conveniently constructing lists ofcalls to compare with call_args_list.
Normally the __class__ attribute of an object will return its type.For a mock object with a spec, __class__ returns the spec classinstead. This allows mock objects to pass isinstance() tests for theobject they are replacing / masquerading as:
The mock classes and the patch() decorators all take arbitrary keywordarguments for configuration. For the patch() decorators the keywords arepassed to the constructor of the mock being created. The keyword argumentsare for configuring attributes of the mock:
Setting the spec of a Mock, MagicMock, or AsyncMockto a class with asynchronous and synchronous functions will automaticallydetect the synchronous functions and set them as MagicMock (if theparent mock is AsyncMock or MagicMock) or Mock (ifthe parent mock is Mock). All asynchronous functions will beAsyncMock.
Mock objects are callable. The call will return the value set as thereturn_value attribute. The default return value is a new Mockobject; it is created the first time the return value is accessed (eitherexplicitly or by calling the Mock) - but it is stored and the same onereturned each time.
If side_effect is a function then whatever that function returns is whatcalls to the mock return. The side_effect function is called with thesame arguments as the mock. This allows you to vary the return value of thecall dynamically, based on the input:
If you want the mock to still return the default return value (a new mock), orany set return value, then there are two ways of doing this. Either returnmock.return_value from inside side_effect, or return DEFAULT:
The patch decorators are used for patching objects only within the scope ofthe function they decorate. They automatically handle the unpatching for you,even if exceptions are raised. All of these functions can also be used in withstatements or as class decorators.
patch() acts as a function decorator, class decorator or a contextmanager. Inside the body of the function or with statement, the targetis patched with a new object. When the function/with statement exitsthe patch is undone.
If new is omitted, then the target is replaced with anAsyncMock if the patched object is an async function ora MagicMock otherwise.If patch() is used as a decorator and new isomitted, the created mock is passed in as an extra argument to thedecorated function. If patch() is used as a context manager the createdmock is returned by the context manager.
target should be a string in the form 'package.module.ClassName'. Thetarget is imported and the specified object replaced with the newobject, so the target must be importable from the environment you arecalling patch() from. The target is imported when the decorated functionis executed, not at decoration time.
Patch can be used as a TestCase class decorator. It works bydecorating each test method in the class. This reduces the boilerplatecode when your test methods share a common patchings set. patch() findstests by looking for method names that start with patch.TEST_PREFIX.By default this is 'test', which matches the way unittest finds tests.You can specify an alternative prefix by setting patch.TEST_PREFIX.
When patch() is creating a mock for you, it is common that the first thingyou need to do is to configure the mock. Some of that configuration can be donein the call to patch. Any arbitrary keywords you pass into the call will beused to set attributes on the created mock:
c80f0f1006