DEV Community

Ruxin Qu
Ruxin Qu

Posted on

JavaScript: Test with mocha

  1. test suite is a collection of tests for a web application. To run a test suite, do npm test
  2. the test file for index.js should be named as index-test.js
  3. testing types:
    • unit test: test the smallest unit of the code
    • integration test: test the interaction between internal services inside the web application
    • End to End test: real user experience
  4. test with mocha:
    • npm init -y to create a package.json file for managing packages.
    • install mocha by npm install mocha -D so it's saved under devDependencies in package.json, which means it's only included during development mode not in the production bundle.
    • change the value of "test" in "script" object to mocha
    • run npm test to start the test
  5. describe and it funcitons accept two parameters, one is the descriptive message, the second one is the call back funciton.
  6. The callback function should has setup, execise, verify and teardown sections.
    • variables are declared in setup section
    • execute functions in execise section
    • and verify the result with the expectedValue
    • teardown makes the tests isolated so it's not affected or affecting other tests.
  7. Hooks can make setup and teardown easier. (Note: The example below works for mocha, it may vary in other test package)
    • beforeEach(callback) callback is run before each test
    • afterEach(callback) callback is run after each test
    • before(callback) callback is run before the first test
    • after(callback) callback is run after the last test
  8. TDD stand for test driven development, it is guided by red-green-refactor cycle. The test is first written, then write the minimum amound of implement code to pass the test and then refactor the code.
  9. code coverage can depend on:
    • function coverage: all the funcitons are called
    • statement coverage: all the statements are run?
    • path coverage: every edge?
    • condition coverage: both the boolean value tested?

reference from codecademy

Top comments (0)