Bird
Raised Fist0
Node.jsframework~10 mins

Writing test cases in Node.js - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Writing test cases
Write test function
↓
Set up inputs
↓
Call function under test
↓
Check output vs expected
↓
Pass or Fail result
↓
Repeat for other cases
↓
Run all tests and report
This flow shows how to write a test: prepare inputs, run the code, check results, and report pass or fail.
Execution Sample
Node.js
const assert = require('assert');

function add(a, b) {
  return a + b;
}

let a = 2;
let b = 3;
let result = add(a, b);
assert.strictEqual(result, 5);
This code tests if the add function returns 5 when given 2 and 3.
Execution Table
StepActionInputFunction CallExpected OutputActual OutputTest Result
1Call add2, 3add(2, 3)55Pass
2Check equalityN/AN/A55Pass
3End testsN/AN/AN/AN/AAll tests passed
💡 All test cases executed and passed successfully.
Variable Tracker
VariableStartAfter Test 1Final
aundefined22
bundefined33
resultundefined55
Key Moments - 2 Insights
Why do we compare actual output to expected output?
Comparing actual to expected output (see execution_table step 2) confirms if the function works correctly.
What happens if the test fails?
If actual output differs from expected, the test fails and reports an error instead of 'Pass' (not shown here but would stop or log failure).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the actual output of add(2, 3)?
A5
B2
C3
Dundefined
💡 Hint
Check the 'Actual Output' column in step 1 of the execution_table.
At which step do we verify if the test passes or fails?
AStep 1
BStep 3
CStep 2
DNo verification step
💡 Hint
Look at the 'Test Result' column in the execution_table.
If add(2, 3) returned 6, how would the test result change in the table?
ATest Result would be 'Pass'
BTest Result would be 'Fail'
CNo change
DTest would be skipped
💡 Hint
Compare expected vs actual output in execution_table step 1.
Concept Snapshot
Writing test cases in Node.js:
- Require assert module
- Write a test function
- Call function with inputs
- Use assert.strictEqual(actual, expected)
- Run tests to see pass/fail
- Repeat for multiple cases
Full Transcript
Writing test cases means checking if your code works as expected. You write a test function, give it inputs, run your code, and compare the output to what you expect. If they match, the test passes. If not, it fails and shows an error. This helps catch mistakes early. In Node.js, you can use the assert module to do this simply. The example shows testing an add function with inputs 2 and 3, expecting 5. The test passes because the actual output matches expected. This process repeats for all test cases to ensure your code is reliable.

Practice

(1/5)
1. What is the main purpose of writing test cases in Node.js projects?
easy
A. To change the code style automatically
B. To make the code run faster
C. To add more comments to the code
D. To check if the code works as expected

Solution

  1. Step 1: Understand the role of test cases

    Test cases are written to verify that the code behaves correctly for different inputs and scenarios.
  2. Step 2: Identify the main goal

    The main goal is to check if the code works as expected, not to improve speed or style.
  3. Final Answer:

    To check if the code works as expected -> Option D
  4. Quick Check:

    Test cases = Verify code correctness [OK]
Hint: Test cases verify code correctness, not speed or style [OK]
Common Mistakes:
  • Thinking test cases improve code speed
  • Confusing test cases with code comments
  • Believing test cases change code style
2. Which of the following is the correct syntax to define a test case using Mocha in Node.js?
easy
A. describe('add function', () => { it('adds numbers', () => { /* test code */ }) })
B. function testAdd() { /* test code */ }
C. test('should add numbers', () => { /* test code */ })
D. runTest('add', () => { /* test code */ })

Solution

  1. Step 1: Recall Mocha test structure

    Mocha uses describe to group tests and it to define individual test cases.
  2. Step 2: Match syntax with options

    describe('add function', () => { it('adds numbers', () => { /* test code */ }) }) correctly uses describe and it with arrow functions.
  3. Final Answer:

    describe('add function', () => { it('adds numbers', () => { /* test code */ }) }) -> Option A
  4. Quick Check:

    Mocha uses describe and it [OK]
Hint: Use describe and it blocks for Mocha tests [OK]
Common Mistakes:
  • Using undefined functions like test() or runTest()
  • Not grouping tests inside describe()
  • Writing test code outside it() blocks
3. Given the following test case using Jest, what will be the output when running the test?
describe('sum function', () => {
  it('adds 2 and 3', () => {
    expect(2 + 3).toBe(5);
  });
  it('adds 2 and 2', () => {
    expect(2 + 2).toBe(5);
  });
});
medium
A. First test passes, second test fails
B. Both tests pass
C. Both tests fail
D. Syntax error, tests do not run

Solution

  1. Step 1: Analyze each test expectation

    The first test expects 2 + 3 to be 5, which is true. The second test expects 2 + 2 to be 5, which is false.
  2. Step 2: Determine test results

    Therefore, the first test passes, and the second test fails.
  3. Final Answer:

    First test passes, second test fails -> Option A
  4. Quick Check:

    Correct expectations = test pass/fail [OK]
Hint: Check each expect() value carefully for pass or fail [OK]
Common Mistakes:
  • Assuming all tests pass without checking values
  • Confusing toBe() with toEqual()
  • Ignoring failing test results
4. Identify the error in this Mocha test code snippet:
describe('multiply function', () => {
  it('multiplies 2 and 3', () => {
    const result = 2 * 3
    expect(result).to.equal(6);
  }
});
medium
A. Incorrect assertion method name
B. Missing closing parenthesis for it() function
C. Using arrow function instead of regular function
D. No error, code is correct

Solution

  1. Step 1: Check parentheses and braces

    The it function is missing a closing parenthesis after the arrow function block.
  2. Step 2: Verify assertion method and function type

    The assertion to.equal is valid in Chai, and arrow functions are allowed in Mocha tests.
  3. Final Answer:

    Missing closing parenthesis for it() function -> Option B
  4. Quick Check:

    Check matching parentheses in test functions [OK]
Hint: Count parentheses carefully in test blocks [OK]
Common Mistakes:
  • Forgetting to close it() parentheses
  • Confusing assertion method names
  • Thinking arrow functions are disallowed
5. You want to write a test case that checks if a function filterPositive correctly returns only positive numbers from an array. Which test case correctly applies this in Jest?
hard
A. it('filters positive numbers', () => { expect(filterPositive([-1,0,2,3])).toBeTruthy(); });
B. it('filters positive numbers', () => { expect(filterPositive([-1,0,2,3])).toBe([2,3]); });
C. it('filters positive numbers', () => { expect(filterPositive([-1,0,2,3])).toEqual([2,3]); });
D. it('filters positive numbers', () => { expect(filterPositive([-1,0,2,3])).toContain(2,3); });

Solution

  1. Step 1: Understand Jest matchers for arrays

    toEqual compares array contents deeply, while toBe checks reference equality, which fails for arrays.
  2. Step 2: Evaluate each option

    it('filters positive numbers', () => { expect(filterPositive([-1,0,2,3])).toEqual([2,3]); }); uses toEqual correctly to check array contents. it('filters positive numbers', () => { expect(filterPositive([-1,0,2,3])).toBe([2,3]); }); uses toBe which fails for arrays. it('filters positive numbers', () => { expect(filterPositive([-1,0,2,3])).toContain(2,3); }); uses toContain incorrectly with multiple values. it('filters positive numbers', () => { expect(filterPositive([-1,0,2,3])).toBeTruthy(); }); only checks truthiness, not exact output.
  3. Final Answer:

    it('filters positive numbers', () => { expect(filterPositive([-1,0,2,3])).toEqual([2,3]); }); -> Option C
  4. Quick Check:

    Use toEqual for array content comparison [OK]
Hint: Use toEqual, not toBe, for comparing arrays in Jest [OK]
Common Mistakes:
  • Using toBe for arrays instead of toEqual
  • Using toContain with multiple values incorrectly
  • Checking only truthiness instead of exact output
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard