From the course: Node.js: Testing and Code Quality

Unlock the full course today

Join today to access over 24,400 courses taught by industry experts.

Mocking functions for test code

Mocking functions for test code

- [Instructor] Jest provides a mechanism known as mock functions for controlling code execution. Jest mock functions can do a few things that are useful for testing codes. They can change the implementation of a function if the original isn't necessary for a test. Mocks can capture calls and parameters for a function for instrumentation. Finally, they can set the return values of a function including throwing, resolving, and rejecting. Jest has three ways of mocking functions and modules. The first foundational method is jest.fn, which mocks a single function. The next is jest.mock, which mocks an entire module. The last is jest.spyOn, which takes an object and a method name. Similar to mock, it mocks the entire module, but it also spies on the given method, Each builds upon the previous, so we'll start with FN. I'll cover the others later in the chapter. Jest.fn creates a new empty mock function. By default, a mock…

Contents