Skip to content

Mocha Chai Assert

Ben Casalino edited this page May 23, 2018 · 2 revisions

Assert/Mocha/Chai/Cypress Libraries: Tools/Libraries and modules used to write unit tests on applications.

Mocha: Library of code that runs the tests (installed already on Cypress) Chai: The assertion Library for Mocha (installed already on Cypress) Assert: default assertion library for Node.js

Mocha/Chai/Assert Example test describe block: describe("#combine", () => { it ("should combine two sets of item data", () => { assert.deepEqual(data.combine(dataSet1, dataSet2), combinedResult) }); });

Setup/Installation:

Note: The package.json file must have “mocha” as the “test” under “scripts”. Note: The package.json file must have “chai” and “mocha” under the devDependencies.

The data.js file contains: The data that is in the file and the functions that are to be tested. The module.exports are listed at the bottom of the file.

The data.test.js file contains: // asserts at the top of the file. // create the data that is to be tested // create the describe/it testing blocks

const assert = require(“assert”); ← to use the node assert library const assert = require(“chai”).assert ← to use chai after installing const data = require(“../data”); ← the data file

How to set up Unit testing with Mocha/Chai/Assert:

  1. Create a node project npm init || npm init -y
  2. Install your testing dependencies npm install mocha chai --save-dev
  3. Create a directory called test
  • Create a file name-of-js-file.test.js
  1. Change the test script to run mocha
  • In your package.json "test": "mocha"
  1. Create a variable named assert and require your preferred assertion library
  2. Write your describe and it blocks
  3. Write your assertion statements
  • Ensure you are pulling in your code using module.exports
  1. Run your tests! Red, Green, Refactor!
Clone this wiki locally