📖 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
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
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
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
Hint
Use after(() => { counter = 0; }); to clean up after tests.
Practice
(1/5)
1. What is the main purpose of the before hook in Node.js testing frameworks like Mocha?
easy
A. To run setup code once before all tests in a suite
B. To run cleanup code after each test
C. To run code before each individual test
D. To skip a test conditionally
Solution
Step 1: Understand the role of before hook
The before hook runs once before all tests in a test suite to prepare the environment.
Step 2: Differentiate from other hooks
beforeEach runs before each test, and after runs after all tests, so they do not match the question.
Final Answer:
To run setup code once before all tests in a suite -> Option A
Quick Check:
before = setup once before all tests [OK]
Hint: Remember: before = once before all tests [OK]
Common Mistakes:
Confusing before with beforeEach
Thinking before runs after tests
Mixing before with afterEach
2. Which of the following is the correct syntax to define a beforeEach hook in Mocha?
easy
A. before_each(() => { /* setup code */ });
B. beforeEach(() => { /* setup code */ });
C. beforeEach {}
D. beforeEach: function() { /* setup code */ }
Solution
Step 1: Recall Mocha hook syntax
Mocha uses functions like beforeEach(() => { ... }) to define hooks.