|
| 1 | +One of the most common criticisms of Mocha is that it doesn't include any assertion tools. |
| 2 | +It is impossible to write meaningful tests without some sort of assertions. |
| 3 | +The idea is that [Node's built-in `assert` module](/tutorials/node/assert) is good enough for most use cases. |
| 4 | + |
| 5 | +```javascript |
| 6 | +const assert = require('assert'); |
| 7 | + |
| 8 | +describe('add', function() { |
| 9 | + it('adds two numbers', function() { |
| 10 | + assert.equal(add(1, 2), 3); |
| 11 | + }); |
| 12 | + |
| 13 | + it('concatenates strings', function() { |
| 14 | + assert.equal(add('hello ', 'world'), 'hello world'); |
| 15 | + }); |
| 16 | +}); |
| 17 | + |
| 18 | +function add(a, b) { |
| 19 | + return a + b; |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +We recommend using Node's built-in `assert` module with Mocha tests by default. |
| 24 | +`assert.ok()`, `assert.equal()`, `assert.strictEqual()`, `assert.throws()`, `assert.rejects()`, and `assert.deepStrictEqual()` cover every assertion we've wanted to write over the last several years. |
| 25 | + |
| 26 | +Alternative Approach: Chai |
| 27 | +---------- |
| 28 | + |
| 29 | +[Chai](/tutorials/mocha/chai) is an assertion library that is commonly used with Mocha. |
| 30 | +Chai exports several different flavors of assertions. |
| 31 | +The [`expect`](https://www.chaijs.com/api/bdd/) flavor is the most common. |
| 32 | + |
| 33 | +```javascript |
| 34 | +const { expect } = require('chai'); |
| 35 | + |
| 36 | +describe('sum()', function() { |
| 37 | + it('adds two numbers', function() { |
| 38 | + // `expect()` takes in a parameter value and returns what Chai calls |
| 39 | + // a "chain" |
| 40 | + expect(add(2, 4)).to.equal(6); |
| 41 | + }); |
| 42 | + |
| 43 | + it('ignores additional arguments', function() { |
| 44 | + expect(add(2, 4, 6)).to.equal(6); |
| 45 | + }); |
| 46 | +}); |
| 47 | + |
| 48 | +function add(a, b) { |
| 49 | + return a + b; |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +Chai's assertions are popular because they read more like English. |
| 54 | +You can write expectations like the following: |
| 55 | + |
| 56 | +```javascript |
| 57 | +expect([1, 2]).to.be.an('array').that.does.not.include(3); |
| 58 | +``` |
| 59 | + |
| 60 | +This syntax can be neat, especially for non-technical readers. |
| 61 | +However, Chai syntax is fairly verbose, and can be difficult to write without practice. |
| 62 | +We recommend using `assert` because `assert`'s API is simpler: you can get by with just 6 functions. |
0 commit comments