mdrndv
mdrndv

Reputation: 175

Typescript: unit tests and dependencies

I am having a hard time setting unit tests for my pet project in Typescript.

Consider following directory structure

/src
   /test
      unittest.ts
      unittest.html
    main.ts 

main.ts:

class Point {
    constructor(public x: number, public y: number) {
    }
}
export { Point };

unittest.ts

import Point from "../main";

function basicTest() {
   let Point = new Point(10, 15);
   // ... 
}

basicTest();

unittest.html

<html>
  <meta charset="UTF-8">
  <head></head>
  <body>
    <script src="unittest.js" charset="utf-8"></script>
  </body>
</html>

After compile this code tsc src/test/unittest.ts && open src/test/unittests.html

I see following error ReferenceError: require is not defined.

I have tried to add requirejs to unittest.html, but it lead to some obscure error. Also I tried to use --module system and --module amd during compilation, but didn't succeed).

Did I miss some dependency?

Thanks!

Upvotes: 0

Views: 159

Answers (2)

mdrndv
mdrndv

Reputation: 175

It seems that the easiest way to resolve dependencies in this case is using browserify and it's plugin tsify:

browserify src/test/unittest.ts -p [ tsify --debug ] > src/test/unittest.js

Upvotes: 0

Pace
Pace

Reputation: 43967

That import line in your test will compile down to something like...

var foo_1 = require("./foo");

The require statement needs to be configured. Javascript doesn't come with module loading support out of the box. There are several different ways that can be done. They are all different approaches on "how do I find the module asked for and load it in." I'll let you do some research on the various module resolution mechanisms in Javascript but there are four main approaches:

  • CommonJS (legacy node/backend mechanism)
  • AMD (legacy browser/frontend mechanism)
  • global (oldest browser approach, doesn't use require, you just reference the dependent library in your HTML with a <script> tag)
  • ES2015 (newer mechanism meant to unify all of these approaches).

If this is a newer project you probably want a tool that supports ES2015 style. RequireJS is a tool for supporting AMD module loading. You might want to look into Webpack or SystemJS which are popular approaches. I work mostly with SystemJS. You don't usually want to configure SystemJS by hand, I would recommend using jspm which does that. You can find a getting started guide here.

If you would rather look at Webpack you can get started here.

Upvotes: 2

Related Questions