Organize JavaScript tests and combine them with explicit assertions.

Before starting: JavaScript functions, assertions and promises.

Practice project: Extend the examples into a small Mocha study demo. Explain the setup, one normal case and one failure or boundary case.

Start here: concepts and guided practice

  1. Mocha: test a boundary

    A useful test checks observable behavior at a decision boundary. The two assertions distinguish a passing score from the nearest failing score.

    Node.js and Mocha installed; save as test/score.cjs and run the local Mocha command.

    const assert = require("node:assert/strict");
    describe("score boundary", () => {
      it("accepts 60 but rejects 59", () => {
        const passed = score => score >= 60;
        assert.equal(passed(59), false);
        assert.equal(passed(60), true);
      });
    });
    Check the output
    The test passes.

    Change >= to >; confirm that the 60 assertion fails.

  2. Mocha: wait for asynchronous work

    An asynchronous test must await or return its promise so the runner can observe completion and failure. This small fake isolates promise handling; it does not test a real network.

    Node.js and Mocha installed; save as test/score.cjs and run the local Mocha command.

    const assert = require("node:assert/strict");
    it("loads an empty report", async () => {
      const load = async () => [];
      assert.deepEqual(await load(), []);
    });
    Check the output
    The asynchronous test passes.

    Return [7] instead and confirm that the assertion fails.

Open the Mocha learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.