0
0
Expressframework~10 mins

Integration vs unit test decision in Express - Interactive Practice

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

Complete the code to define a unit test that mocks the database call.

Express
test('should return user data', () => {
  const mockDb = jest.fn().mockReturnValue({ id: 1, name: 'Alice' });
  const result = getUser([1]);
  expect(result.name).toBe('Alice');
});
Drag options to blanks, or click blank then click option'
AmockDb
BmockDb()
CdbCall()
DdbCall
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the mock function immediately instead of passing it.
Passing the real database call instead of the mock.
2fill in blank
medium

Complete the code to write an integration test that sends a request to the Express app.

Express
const request = require('supertest');
const app = require('./app');

test('GET /users returns 200', async () => {
  const response = await request(app).[1]('/users');
  expect(response.statusCode).toBe(200);
});
Drag options to blanks, or click blank then click option'
Adelete
Bpost
Cput
Dget
Attempts:
3 left
💡 Hint
Common Mistakes
Using post instead of get for a GET request.
Forgetting to await the request.
3fill in blank
hard

Fix the error in the unit test by completing the mock setup correctly.

Express
jest.mock('./db', () => ({
  fetchUser: jest.fn().[1]({ id: 2, name: 'Bob' })
}));
Drag options to blanks, or click blank then click option'
AmockReturnValue
BmockImplementation
CmockResolvedValue
DmockReturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using mockReturnValue for async functions.
Using a non-existent mockReturn method.
4fill in blank
hard

Fill both blanks to create a test that checks the response body and status code in an integration test.

Express
test('POST /login returns token', async () => {
  const response = await request(app).post('/login').send({ username: 'user', password: 'pass' });
  expect(response.statusCode).toBe([1]);
  expect(response.body).toHaveProperty([2]);
});
Drag options to blanks, or click blank then click option'
A200
B'token'
C'error'
D201
Attempts:
3 left
💡 Hint
Common Mistakes
Using status code 201 which means created, not typical for login.
Checking for 'error' property instead of 'token'.
5fill in blank
hard

Fill all three blanks to write a unit test that mocks a service call and verifies the result.

Express
const service = require('./service');

jest.mock('./service');

test('should return processed data', async () => {
  service.processData.mock[1]({ success: true });
  const result = await processHandler([2]);
  expect(result).toEqual([3]);
});
Drag options to blanks, or click blank then click option'
AResolvedValue
B'inputData'
C{ success: true }
DReturnValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using mockReturnValue for async functions.
Passing wrong input data to the handler.
Expecting wrong output object.