0
0
Node.jsframework~30 mins

Test lifecycle hooks (before, after) in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Test lifecycle hooks (before, after) in Node.js
📖 Scenario: You are writing tests for a simple calculator module in Node.js. You want to prepare some setup before tests run and clean up after all tests finish.
🎯 Goal: Build a test file using before and after hooks to initialize and reset a variable around your tests.
📋 What You'll Learn
Create a variable counter initialized to 0
Use a before hook to set counter to 5 before tests
Write a test that checks counter equals 5
Use an after hook to reset counter to 0 after tests
💡 Why This Matters
🌍 Real World
Test lifecycle hooks help prepare and clean up resources like database connections or test data before and after tests run.
💼 Career
Understanding test hooks is essential for writing reliable automated tests in Node.js projects, a common skill in software development jobs.
Progress0 / 4 steps
1
DATA SETUP: Create a variable counter initialized to 0
Create a variable called counter and set it to 0.
Node.js
Need a hint?

Use let counter = 0; to create the variable.

2
CONFIGURATION: Add a before hook to set counter to 5
Add a before hook that sets counter to 5 before tests run.
Node.js
Need a hint?

Use before(() => { counter = 5; }); to set up before tests.

3
CORE LOGIC: Write a test that checks counter equals 5
Write a test using it named 'counter should be 5' that asserts counter === 5 using strictEqual from assert.
Node.js
Need a hint?

Use it('counter should be 5', () => { assert.strictEqual(counter, 5); }); to write the test.

4
COMPLETION: Add an after hook to reset counter to 0
Add an after hook that resets counter to 0 after all tests run.
Node.js
Need a hint?

Use after(() => { counter = 0; }); to clean up after tests.