0
0
Expressframework~10 mins

Mocking database calls in Express - Interactive Code Practice

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

Complete the code to import the mocking library for testing database calls.

Express
const [1] = require('sinon');
Drag options to blanks, or click blank then click option'
Ajest
Bexpress
Cmongoose
Dsinon
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'express' instead of a mocking library.
Confusing 'mongoose' (database ORM) with mocking tools.
2fill in blank
medium

Complete the code to stub the database method findUser to return a fake user.

Express
const stub = sinon.[1](db, 'findUser').returns({ id: 1, name: 'Test User' });
Drag options to blanks, or click blank then click option'
Astub
Bmock
Cspy
Dfake
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'mock' which is different from 'stub' in Sinon.
Using 'spy' which only observes calls but does not replace behavior.
3fill in blank
hard

Fix the error in restoring the stub after the test to avoid side effects.

Express
stub.[1]();
Drag options to blanks, or click blank then click option'
Areset
Bclear
Crestore
DresetHistory
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'reset' which only resets call history but does not restore original function.
Using 'clear' which is not a Sinon method.
4fill in blank
hard

Fill both blanks to create a mock Express route that uses the stubbed database call and sends a JSON response.

Express
app.get('/user', async (req, res) => {
  const user = await db.[1]();
  res.[2](user);
});
Drag options to blanks, or click blank then click option'
AfindUser
Bsend
Cjson
DgetUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' instead of 'json' which may send data but not set JSON content type.
Using wrong database method name like 'getUser'.
5fill in blank
hard

Fill all three blanks to write a test that stubs the database call, calls the route handler, and asserts the response.

Express
const stub = sinon.[1](db, 'findUser').returns({ id: 2, name: 'Mocked' });

await request(app).get('/user').expect(200).expect(res => {
  if (res.body.name !== [2]) throw new Error('Wrong user');
});
stub.[3]();
Drag options to blanks, or click blank then click option'
Astub
B'Mocked'
Crestore
Dmock
Attempts:
3 left
💡 Hint
Common Mistakes
Not restoring the stub after the test.
Checking for the wrong user name string.
Using 'mock' instead of 'stub' for replacing the function.