https://testingjavascript.com/courses/fundamentals-of-testing-in-javascript
-
Throw an Error with a Simple Test in JavaScript
$ node 01-throw-an-error.js
Throwing an error when a condition fails is the most fundamental aspect of a test.
-
Abstract Test Assertions into a JavaScript Assertion Library
$ node 02-abstract-assertions.js
An assertion library can be as simple as a function which takes a result and returns an object containing a number of different assertions which allows the user to determine how they want to evaluate that result against an expected value.
-
Encapsulate and Isolate Tests by building a JavaScript Testing Framework
$ node 03-encapsulate-and-isolate-tests.js
Our naive implementation works, but prevents subsequent errors from being thrown. Additionally, the stack trace indicates the issue is at the location where the error was thrown. A better solution would be to allow tests to continue running beyond the failed ones, and indicates which test is revealing and issue.
This can be fixed by creating a function which takes a title, allowing us to name tests, and a callback function which will be responsible for running the actual tests, and making use of a try-catch block so as to prevent thrown errors from stopping further execution.
-
Support Async Tests with JavaScripts Promises through async await
$ node 04-support-async-tests.js
In order to allow async tests to be run, we need our
testfunction to beasync, and we need to prepend the callack invocation withawait. -
Provide Testing Helper Functions as Globals in JavaScript
$ node --require ./setup-globals.js 05-provide-testing-helpers-as-globals.js
Because of the usefulness of test utilities one could extract them into a module and import them everywhere.
Another strategy, because we're in a test environment and globals are pragmatic in this situation, is to make the helpers available globally.
The
--require ./[file].jsflag allows files to be required before executing scripts with thenodecommand -
Verify Custom JavaScript Tests with Jest
$ npx jest
We've implemented the Jest API in our tests, so we can instead run Jest.