Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to test a function with a mock function?


Asked by Priscilla Lozano on Dec 04, 2021 FAQ



Let's imagine we're testing an implementation of a function forEach, which invokes a callback for each item in a supplied array. To test this function, we can use a mock function, and inspect the mock's state to ensure the callback is invoked as expected.
Furthermore,
There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a manual mock to override a module dependency. Let's imagine we're testing an implementation of a function forEach, which invokes a callback for each item in a supplied array.
Also Know, Enter mock functions, the procedural language version of mock objects ("Endo-Testing: Unit Testing with Mock Objects", Mackinnon, et. al.), that can help facilitate testing these hard-to-reach portions of your code. In a procedural language like C there are a couple of difficulties in separating out units to test:
Also,
jest.fn () can be called with an implementation function as an optional argument. If an implementation is provided, calling the mock function will call the implementation and return it's return value. If no implementation is provided, calling the mock returns undefined because the return value is not defined.
In respect to this,
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. Subsets of a module can be mocked and the rest of the module can keep their actual implementation: