|
| 1 | +# JavaScript Unit Testing Examples |
| 2 | + |
| 3 | +Example project to allow me to show how best to unit test a JavaScript Express application. |
| 4 | + |
| 5 | +## Install |
| 6 | + |
| 7 | +Clone this repository and install the dependencies as follows: |
| 8 | + |
| 9 | +``` |
| 10 | +git clone git@github.com:MarcL/js-unit-testing-framework.git |
| 11 | +npm install |
| 12 | +``` |
| 13 | + |
| 14 | +## Running the tests |
| 15 | + |
| 16 | +The code sets up a basic Express server with a few routes and some tests which cover testing the server setup. Run the test suite using npm: |
| 17 | + |
| 18 | +``` |
| 19 | +npm test |
| 20 | +``` |
| 21 | + |
| 22 | +## JavaScript Tests |
| 23 | + |
| 24 | +Take a look in the `test` directory to see all of the test code. There are lots of examples of different types of tests and how to create them. |
| 25 | + |
| 26 | +### Asynchronous functions and promises |
| 27 | + |
| 28 | +Some examples of how to test asynchronous functions and promises, including some tips and tricks and gotchas. |
| 29 | + |
| 30 | +#### Asynchronous function |
| 31 | +- Timeout because `done` callback isn't called when function succeeds |
| 32 | +- Passing test but slow because timer isn't stubbed |
| 33 | +- Passing test and fast because timer is stubbed |
| 34 | +- Timeout because `done` callback isn't called when function throws an error |
| 35 | +- Passing test to call `done` callback when function throws an error |
| 36 | + |
| 37 | +#### Promise : resolving |
| 38 | +- Test passes incorrectly because Promise isn't returned |
| 39 | +- Passing test because promise is returned |
| 40 | +- Passing test because `done` callback is called after resolution |
| 41 | +- Passing test because `done` callback is called after resolution using `chai-as-promised` syntax |
| 42 | + |
| 43 | +#### Promise : rejecting |
| 44 | +- Test passes incorrectly because Promise isn't returned |
| 45 | +- Failing test because rejected Promise error isn't caught |
| 46 | +- Passing test because Promise is returned and rejection is caught |
| 47 | +- Passing test because Promise rejection is caught and `done` callback is called |
| 48 | +- Passing test because Promise rejection is caught and `done` callback is called using `chai-as-promised` syntax |
| 49 | + |
| 50 | +#### Slow tests |
| 51 | +- Passing test but is slow due to Promise function in chain taking a long time |
| 52 | +- Passing test and much faster as longer function is now stubbed to execute immediately |
| 53 | + |
| 54 | +## License |
| 55 | + |
| 56 | +See [LICENSE](LICENSE) |
0 commit comments