https://github.com/martinlaws/intro-to-tdd
https://github.com/martinlaws/intro-to-tdd
Last synced: 2 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/martinlaws/intro-to-tdd
- Owner: martinlaws
- Created: 2020-02-10T04:22:58.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2022-12-30T19:38:24.000Z (over 2 years ago)
- Last Synced: 2025-01-26T08:15:50.725Z (4 months ago)
- Language: JavaScript
- Size: 2 MB
- Stars: 0
- Watchers: 1
- Forks: 1
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# TDD with Mocha & Chai
> Big props to [andydlindsay](https://github.com/andydlindsay) @ LHL Vancouver for parts of these notes/demo ✊
### Agenda
- [x] Modules & `npm`, a ❤️ story
- [x] Practicing unit testing using a Test-Driven Development (TDD) methodology
- [x] Using the Mocha BDD test framework
- [x] Using the Chai assertion library
- [x] Creating and consuming modules using Node's default CommonJS sytax (`module.exports` and `require`)### TDD
- **T**est **D**riven **D**evelopment
- Tests are written before the code is written
- We use a process called Red-Green-Refactor
- Red: The test is failing
- Green: The test is passing
- Refactor: Improve the existing code safe in the knowledge that the functionality is testable
- BDD: **B**ehaviour **D**riven **D**evelopment
- Very similar to TDD, but the focus is more on the end user rather than the quality of the code under test### Mocha
- A testing framework
- By default, looks in the `test` folder for test files to run### Chai
- An **assertion** library
- We can use _assertions_ to describe the desired outcome of our code
- Chai offers three different interfaces `should`, `expect`, and `assert`
- For most uses, choosing which interface to use is a matter of preference```js
// should
myVar.should.be.a("string");
myVar.should.equal("hello world");// expect
expect(myVar).to.be.a("string");
expect(myVar).to.equal("hello world");// assert
assert.typeOf(myVar, "string");
assert.equal(myVar, "hello world");
```### `module.exports` and `require`
- We can export functions, objects, etc from a file using the `module.exports` object
- You can add new keys to the `module.exports` object _or_ you can completely overwrite it with a function/object```js
// adding new keys to module.exports
module.exports.myFunc = myFunc;
module.exports.myOtherFunc = myOtherFunc;// overwriting module.exports object
module.exports = myFunc;
// or
module.exports = {
myFunc,
myOtherFunc
};
```- As you have previously seen, we can bring functions, objects, etc into a file using `require`
```js
// basic require syntax
const myFunc = require("./myFunc");// if the file exports an object, we can use ES6 destructuring
const { myFunc } = require("./myFunc");
```### Useful Links
- [Mocha Docs](https://mochajs.org/)
- [Chai Docs](https://www.chaijs.com/)
- [Chai: Differences between should, expect, and assert](https://www.chaijs.com/guide/styles/#differences)