0
0
Node.jsframework~5 mins

Mocking modules and functions in Node.js - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is mocking in the context of Node.js testing?
Mocking means creating fake versions of modules or functions to control their behavior during tests. It helps isolate the code being tested by replacing real dependencies with controlled stand-ins.
Click to reveal answer
beginner
How does mocking a module help in testing?
Mocking a module lets you replace its real behavior with fake responses. This avoids side effects like network calls or database access, making tests faster and more reliable.
Click to reveal answer
beginner
Which Node.js testing library is commonly used for mocking functions and modules?
Jest is a popular testing library that includes built-in support for mocking functions and modules easily with simple APIs.
Click to reveal answer
intermediate
What does jest.mock('moduleName') do?
It tells Jest to replace the real module named 'moduleName' with a mock version during tests. You can then control what the mock returns or how it behaves.
Click to reveal answer
intermediate
How can you mock a single function inside a module without mocking the entire module?
You can import the module normally and then use jest.spyOn(module, 'functionName') to replace just that function with a mock, allowing you to control or check its calls.
Click to reveal answer
What is the main purpose of mocking in Node.js tests?
ATo replace real dependencies with controlled fake versions
BTo speed up the Node.js runtime
CTo write code without errors
DTo deploy applications faster
Which Jest function is used to mock an entire module?
Ajest.spyOn()
Bjest.mock()
Cjest.fn()
Djest.replace()
How do you mock a single function inside a module without mocking the whole module?
AUse jest.mock() on the module
BUse jest.replace() on the function
CUse jest.spyOn() on the function
DUse jest.fn() globally
Why is mocking useful when a module makes network requests?
ATo log network data
BTo test network speed
CTo increase network traffic
DTo avoid real network calls during tests
What does jest.fn() do?
ACreates a new mock function
BMocks an entire module
CRuns a test suite
DImports a module
Explain how you would mock a module and a single function inside a module in Node.js tests using Jest.
Think about replacing dependencies to control test behavior.
You got /4 concepts.
    Describe why mocking is important in testing Node.js applications that use external services like databases or APIs.
    Consider what happens if tests depend on real external services.
    You got /4 concepts.