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
From the course: Node.js: Testing and Code Quality
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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
-
(Locked)
Replacing code with test doubles6m 51s
-
(Locked)
Mocking functions for test code7m 1s
-
(Locked)
Writing your first Jest mock5m 46s
-
(Locked)
Mock an entire module with Jest7m 22s
-
(Locked)
Mocking module dependencies6m 19s
-
(Locked)
Spying to observe interactions7m 3s
-
(Locked)
Challenge: Mock a successful reservation creation53s
-
(Locked)
Solution: Mock a successful reservation creation6m 11s
-
(Locked)
-
-