Problem B is a bit more subtle. When you use TypeScript for a web page, the output get compiled in a monolithic file using some module system (in my case the require.js AMD format). When you test it, instead, you run your code in a Node.js instance that can not understand the AMD format (and you get the infamous
define is not defined error).
Fortunately, we can solve these issues very easily. Let’s go step by step. Suppose you have a
tsconfig.json file like this:
The first step is to install all the tools we need. I will use **mocha, chai, ts-node ** and amd-loader.
The first two are one of the many suites for unit testing.
ts-node is a tool for compiling on-the-fly TypeScript code commands. Imagine it as a REPL for TypeScript, it works exactly as
node but you can write in TS. The last one,
amd-loader is a tool that allow use to run
mocha on the AMD output blob.
Now, we will install the type definitions for
We need these for writing TypeScript unit test (Problem A). At this point, we can create a folder
tests and write our first test.
If we need to import a custom function from our code base, we can use the usual TypeScript
Now we need to run the tests with the following command:
As you can see, before running tests, we need to tell
mocha to “import” two libraries.
ts-node/register, so that
mocha can “understand” TypeScript code; and
amd-loader, so that
mocha can import AMD bundled modules.