0
0
Node.jsframework~10 mins

Testing async code 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 declare an async function.

Node.js
async function fetchData() {
  const data = await [1]();
  return data;
}
Drag options to blanks, or click blank then click option'
AloadData
BfetchData
CgetData
DretrieveData
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-async function with await causes errors.
Calling a function that does not return a promise.
2fill in blank
medium

Complete the code to test an async function using Jest.

Node.js
test('fetchData returns data', async () => {
  const data = await fetchData();
  expect(data).[1]('value');
});
Drag options to blanks, or click blank then click option'
AtoBe
BtoEqual
CtoContain
DtoHaveLength
Attempts:
3 left
💡 Hint
Common Mistakes
Using toBe for object comparison causes test failures.
Forgetting to use async/await in the test function.
3fill in blank
hard

Fix the error in the async test by completing the code.

Node.js
test('fetchData throws error', async () => {
  await expect(fetchData()).[1]();
});
Drag options to blanks, or click blank then click option'
Arejects.toThrow
Bresolves.toThrow
Cresolves.toBe
Drejects.toBe
Attempts:
3 left
💡 Hint
Common Mistakes
Using resolves when expecting an error causes false positives.
Not awaiting the expect call leads to unhandled promise rejections.
4fill in blank
hard

Fill both blanks to correctly mock an async function with Jest.

Node.js
jest.mock('./api');
const api = require('./api');

api.fetchData = jest.fn().[1](() => Promise.[2]('mocked data'));
Drag options to blanks, or click blank then click option'
AmockImplementation
BmockResolvedValue
Cresolve
DmockRejectedValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using mockRejectedValue when expecting success.
Using mockImplementation without returning a promise.
5fill in blank
hard

Fill all three blanks to write a complete async test with setup and teardown.

Node.js
beforeEach(() => {
  jest.[1]();
});

afterEach(() => {
  jest.[2]();
});

test('async fetchData test', async () => {
  const data = await fetchData();
  expect(data).[3]('result');
});
Drag options to blanks, or click blank then click option'
AclearAllMocks
BresetAllMocks
CtoContain
DtoBe
Attempts:
3 left
💡 Hint
Common Mistakes
Not clearing mocks before tests causes interference.
Using toBe when checking for substring presence.