0
0
Node.jsframework~10 mins

Mocking modules and functions in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to mock a function using Jest.

Node.js
const myFunc = jest.[1]();
Drag options to blanks, or click blank then click option'
Afn
BmockFn
CmockFunction
DspyOn
Attempts:
3 left
💡 Hint
Common Mistakes
Using jest.mockFn() which does not exist.
Using jest.spyOn() which is for spying, not creating a mock function.
2fill in blank
medium

Complete the code to mock the entire 'fs' module in Jest.

Node.js
jest.[1]('fs');
Drag options to blanks, or click blank then click option'
Amock
BspyOn
Cfn
DrequireMock
Attempts:
3 left
💡 Hint
Common Mistakes
Using jest.spyOn() which is for spying on functions, not mocking modules.
Using jest.fn() which mocks functions, not modules.
3fill in blank
hard

Fix the error in spying on a method 'readFile' of the 'fs' module.

Node.js
const fs = require('fs');

jest.[1](fs, 'readFile').mockImplementation((path, cb) => cb(null, 'data'));
Drag options to blanks, or click blank then click option'
AmockFunction
Bmock
Cfn
DspyOn
Attempts:
3 left
💡 Hint
Common Mistakes
Using jest.mock() which replaces the whole module, not spying on a method.
Using jest.fn() which creates a new mock function but does not spy on existing ones.
4fill in blank
hard

Fill both blanks to mock a function and set its return value.

Node.js
const mockFunc = jest.[1]();
mockFunc.[2](() => 42);
Drag options to blanks, or click blank then click option'
Afn
BmockReturnValue
CmockImplementation
DspyOn
Attempts:
3 left
💡 Hint
Common Mistakes
Using spyOn for creating a new mock function.
Using mockReturnValue instead of mockImplementation when a function is needed.
5fill in blank
hard

Fill all three blanks to mock a module, spy on a method, and restore the original after test.

Node.js
jest.[1]('axios');
const axios = require('axios');
const spy = jest.[2](axios, 'get');

// After test
spy.[3]();
Drag options to blanks, or click blank then click option'
Amock
BspyOn
CmockRestore
Dfn
Attempts:
3 left
💡 Hint
Common Mistakes
Using jest.fn() to mock the whole module.
Forgetting to restore the original method after spying.