Hello World with TypeScript and JSX

If you're looking for a solid TypeScript JSX tutorial this is a great resource.

Last night I wanted to play with TypeScripts new support for JSX. In this post I'll walk through my process, and what I learned along the way. Hopefully you find this useful.

While it doesn't yet exist in the current version (at the time of this writing TypeScript is at 1.5), you can however grab a copy of the nightly builds from npm.

Get the most recent nightly build.

npm install -g typescript@next

The rest of this post was run against nightly build Version 1.6.0-dev.20150814.

Given this sample React/JSX

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.render(<HelloMessage name="John" />, mountNode);

Create a TypeScript version of a JSX file.

Just like how TypeScript doesn't read .js but looks for .ts files (unless you hack it). TypeScript doesn't read .jsx files. It instead looks for .tsx files.

So if you save the above sample as a helloWorld.tsx, we can then run the tsc compiler against our helloWorld.tsx file.

If I run tsc helloWorld.tsx I get the following errors:

> tsc helloWorld.tsx
helloWorld.tsx(1,20): error TS2304: Cannot find name 'React'.
helloWorld.tsx(3,12): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
helloWorld.tsx(7,1): error TS2304: Cannot find name 'React'.
helloWorld.tsx(7,14): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
helloWorld.tsx(7,44): error TS2304: Cannot find name 'mountNode'.

Working through the errors...

I could just show you the final output that compiles, but want to include my learning process (stumbling) as I fumble through and figure out the new command.

Fixing error TS2304: Cannot find name 'React'.

If you've been using TypeScript for any amount of time, the first error should be easy to see. The compiler knows nothing about this thing called React. And I haven't used React with TypeScript before. I don't want to go write a bunch of TypeScript type definitions for react and can easily pull down ones created already by using tsd to install the Definitely Typed definitions for React.

What is tsd?

If you haven't seen TSD before it's a great package manger utility for TypeScript Type Definitions.

It can be easily installed with npm install -g tsd.

Installing React Type Definitions

tsd install react which tsd will download from Definitely Typed the react.d.ts and place it in ./typings/react/react.d.ts.

I then reference the file in our helloWorld.tsx which gives me the following:

/// <reference path="./typings/react/react.d.ts" />

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.render(<HelloMessage name="John" />, mountNode);

When I re-run tsc helloWorld.tsx hoping to get rid of the first error: hmmm

> tsc helloWorld.tsx
helloWorld.tsx(3,20): error TS2304: Cannot find name 'React'.
helloWorld.tsx(5,12): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
helloWorld.tsx(9,1): error TS2304: Cannot find name 'React'.
helloWorld.tsx(9,14): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
helloWorld.tsx(9,44): error TS2304: Cannot find name 'mountNode'.

Well, that didn't get rid of our error TS2304: Cannot find name 'React'.. This threw me for a bit but eventually figured out that you need set it up by adding import React = __React;.

So that gives us this:

/// <reference path="./typings/react/react.d.ts" />
import React = __React;

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.render(<HelloMessage name="John" />, mountNode);

Now we should see some errors going away. And we do...

> tsc helloWorld.tsx
helloWorld.tsx(6,12): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
helloWorld.tsx(10,14): error TS2607: JSX element class does not support attributes because it does not have a 'props' property
helloWorld.tsx(10,14): error TS17004: Cannot use JSX unless the '--jsx' flag is provided.
helloWorld.tsx(10,44): error TS2304: Cannot find name 'mountNode'.

Fixing error TS17004: Cannot use JSX unless the '--jsx' flag is provided.

The next error is new to me, but it makes some sense, so I add the --jsx flag to tsc and try tsc --jsx helloWorld.tsx, but looks like I missed a parameter to --jsx.

> tsc --jsx helloWorld.tsx
message TS6081: Argument for '--jsx' must be 'preserve' or 'react'.

In the current iteration of TypeScript 1.6 appears to have two options for --jsx, both preserve or react.

  • preserve will keep the jsx in the output. I presume this is so you can use tools like JSX to actually provide the translation.
  • react will remove the jsx syntax and turn it in to plain javascript so <div></div> in the TSX file would become React.createElement("div", null).

By passing the react option, here's where we end up:

> tsc --jsx react helloWorld.tsx
helloWorld.tsx(11,14): error TS2607: JSX element class does not support attributes because it does not have a 'props' property
helloWorld.tsx(11,44): error TS2304: Cannot find name 'mountNode'.

I'm going to tackle the last error next, as initially I didn't understand the JSX error above.

Fixing error TS2304: Cannot find name 'mountNode'.

This one I'll just make the compiler happy and presume we defined mountNode as an html element probably a <div id="mountNode"></div> somewhere in the global scope to keep this example short.

I place declare var mountNode: any; near the top of my helloWorld.tsx file and we're left with one last error:

> tsc --jsx react helloWorld.tsx
helloWorld.tsx(10,14): error TS2607: JSX element class does not support attributes because it does not have a 'props' property

Fixing error TS2607: JSX element class does not support attributes because it does not have a 'props' property

This last error is actually the one that had me stumped, and mostly why I'm writing this lengthy post so I hope you find it and can work through it a little quicker than it took me.

What's happening here is TypeScript is doing what it was intended to do. It's statically checking our JSX in this case.

If you look at our sample above where we call React.createClass(...) and compare that to the type definition we see: function createClass<P, S>(spec: ComponentSpec<P, S>): ClassicComponentClass<P>; you may notice P and S generic parameters to createClass<P, S> which I didn't supply earlier.

The naming here wasn't immediately obvious, but some snooping around in the type definitions and I eventually found out P is referring to the type we pass in defining the structure of the react props and S defines the state.

So in this Hello World example when we placed name="John" attribute inside the <HelloMessage name="John" /> element and since we didn't give a P or S to the React.createClass<P,S>(...), TypeScript was providing static type checking against an unknown type for P & S. In this case saying that we can't apply the attributes to the element because we did not provide a generic type P to define what props are allowed to be included.

To fix this I create a type by using an interface like below:

interface HelloWorldProps {
  name: string;
}

When I call React.createClass I pass in the HelloWorldProps interface for the props (P) and an any for the state (S) like so: React.createClass<HelloWorldProps, any>(...)

YAY IT COMPILES!!!

Compiling the below by using tsc --jsx react helloWorld.tsx

/// <reference path="./typings/react/react.d.ts" />
import React = __React;
declare var mountNode: any;

interface HelloWorldProps {
  name: string;
}

var HelloMessage = React.createClass<HelloWorldProps, any>({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.render(<HelloMessage name="John" />, mountNode);

We get the following output in helloWorld.js

/// <reference path="./typings/react/react.d.ts" />
var React = __React;
var HelloMessage = React.createClass({
    render: function () {
        return React.createElement("div", null, "Hello ", this.props.name, React.createElement("div", null));
    }
});
React.render(React.createElement(HelloMessage, {"name": "John"}), mountNode);

Let's improve it now...

Since we started with a plain JavaScript version of our sample and we're now using TypeScript we get to take advantage of some of what TypeScript brings to the table.

But before we do this, let's first break our code (from a compiler) perspective to see what the above gave us...

Let's break our example on purpose to see how TypeScript responds?

I changed one character in two places in the working helloWorld.tsx file and when I run the compiler I get the following two errors. Can you spot what changed?

/// <reference path="./typings/react/react.d.ts" />
import React = __React;
declare var mountNode: any;

interface HelloWorldProps {
  Name: string;
}

var HelloMessage = React.createClass<HelloWorldProps, any>({
  render: function() {
    return <div>Hello {this.props.mane} <div></div></div>;
  }
});

React.render(<HelloMessage name="John" />, mountNode);

Output:

> tsc --jsx react helloWorld.tsx
helloWorld.tsx(15,14): error TS2324: Property 'Name' is missing in type 'HelloWorldProps'.
helloWorld.tsx(15,28): error TS2339: Property 'name' does not exist on type 'HelloWorldProps'.

Did you spot the change made? If you did, amazing. If you didn't, don't feel bad - it's a very simple and easy error to make when writing plain javascript. One that can't be found without actually executing plain JS, debugging, running unit tests or other checkers before even finding the error.

If you didn't spot the change by looking directly at the code, can you spot the change by reading the compiler error output?

Ok, give up? - I changed the name to Name in the HelloWorldProps interface definition AND in the JSX this.props.mane I spelled the props name mane wrong (should be Name according to our interface definition). So then why did we only get the error on line 15 (that's the React.render(...) line).

TypeScript in this case is using the HelloWorldProps interface and it's definition to type-check the attributes used in the JSX <HelloMessage />.

This is great, the compiler found the error right in the JSX before we even tried to execute the code.

Why didn't it detect the mane mis-spelled variable?

I'm going to just take a guess on this one but I'm not a React guy yet, so it may have something to do with react internals (that I'm not feeling like digging into at the moment).

If you look at the react.d.ts you'll see that React.createClass<P,S>() returns a type of ClassicComponentClass<P>.

Thanks to a tip from Ryan (ya, the famous Ryan from the TypeScript team) has a great write up about TypeScript and JSX we should be avoiding all of the above use of React.createClass(...) and instead using the ES6 extends functionality which we can leverage in TypeScript.

Let's re-write...

Turning the HelloMessage variable into an ES6 class we now also get type checking inside the component on this.props options. YAY!!!:

/// <reference path="./typings/react/react.d.ts" />
import React = __React;
declare var mountNode: any;

interface HelloWorldProps extends React.Props<any> {
  Name: string;
}

class HelloMessage extends React.Component<HelloWorldProps, {}> {
  render() {
    return <div>Hello {this.props.mane}</div>;
  }
}

React.render(<HelloMessage name="John" />, mountNode);

The above gives us the following errors:

> tsc --jsx react helloWorld.tsx
helloWorld.tsx(11,35): error TS2339: Property 'mane' does not exist on type 'HelloWorldProps'.
helloWorld.tsx(15,14): error TS2324: Property 'Name' is missing in type 'HelloWorldProps'.
helloWorld.tsx(15,28): error TS2339: Property 'name' does not exist on type 'HelloWorldProps'.

Final Answer

So, a bit long winded, but below is the final sample HelloWorld React TypeScript JSX prototype.

/// <reference path="./typings/react/react.d.ts" />
import React = __React;
declare var mountNode: any;

interface HelloWorldProps extends React.Props<any> {
  name: string;
}

class HelloMessage extends React.Component<HelloWorldProps, {}> {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

React.render(<HelloMessage name="John" />, mountNode);

Wrap-up

While it seemed a bit challenging getting started with TypeScript and JSX I could really see the benefit of the compiler helping out with React components going forward, and look forward to the future of this part of the project.

Thanks to the TypeScript team and community that helped bring all of this support together!

Happy TSXing!

Read More

Debugging iOS AutoLayout Issues

This tip may not be news to you, but it was to me so I'll put this up here to help you, but more to help myself when I get stuck down the road and forget how to do this.

Background

I just stumbled upon a way to help when debugging and diagnosing issues around ambiguous auto layout constraints (you know the kind where iOS just picks the one it feels like to remove?).

Today I was researching why I was receiving the following output in my debugger console:

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x7fc82d3e18a0 H:[UIView:0x7fc82aba1210(768)]>",
    "<NSLayoutConstraint:0x7fc82d6369e0 H:[UIView:0x7fc82aba1210]-(0)-|   (Names: '|':UIView:0x7fc82d6b9f80 )>",
    "<NSLayoutConstraint:0x7fc82d636a30 H:|-(0)-[UIView:0x7fc82aba1210]   (Names: '|':UIView:0x7fc82d6b9f80 )>",
    "<NSLayoutConstraint:0x7fc82d3e7fd0 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7fc82d6b9f80(50)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7fc82d3e18a0 H:[UIView:0x7fc82aba1210(768)]>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

Now, I can tell from the above that theres an issue with the height constraint(s), but looking at this, I have no idea what view is being referenced which makes it quite difficult to jump to XCode and inspect the view's constraints.

But I worked through it, and learned the following along the way. Hope this helps you.

How to set auto layout breakpoint in Xcode debugger

Using this text Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. I found this great post on stack overflow on How to trap on UIViewAlertForUnsatisfiableConstraints but have copied below for reference.

You'll want to add a Symbolic Breakpoint. Apple provides an excellent guide on how to do this.

  1. Open the Breakpoint Navigator cmd+7
  2. Click the Add button in the lower left
  3. Select Add Symbolic Breakpoint...
  4. Where it says Symbol just type in UIViewAlertForUnsatisfiableConstraints

You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.

But that's only the first step. Once you've run the app and hit the breakpoint, you're left staring at assembly code and memory addresses, for example:

UIKit`UIViewAlertForUnsatisfiableConstraints:
->  0x1131cc4a2 <+0>:   pushq  %rbp
    0x1131cc4a3 <+1>:   movq   %rsp, %rbp
    0x1131cc4a6 <+4>:   pushq  %r15
    0x1131cc4a8 <+6>:   pushq  %r14
    0x1131cc4aa <+8>:   pushq  %rbx
    0x1131cc4ab <+9>:   pushq  %rax
    0x1131cc4ac <+10>:  movq   %rsi, %r14
    0x1131cc4af <+13>:  movq   %rdi, %r15
    0x1131cc4b2 <+16>:  cmpq   $-0x1, 0x778796(%rip)     ; _UIConstraintBasedLayoutPlaySoundOnUnsatisfiable.result + 7
    0x1131cc4ba <+24>:  jne    0x1131cc529               ; <+135>
    0x1131cc4bc <+26>:  cmpb   $0x0, 0x778785(%rip)      ; _UIConstraintBasedLayoutPlaySoundWhenEngaged.__once + 7
    0x1131cc4c3 <+33>:  je     0x1131cc4ed               ; <+75>
    0x1131cc4c5 <+35>:  movq   0x73cd8c(%rip), %rdi      ; (void *)0x0000000113925248: UIDevice
    0x1131cc4cc <+42>:  movq   0x7108e5(%rip), %rsi      ; "currentDevice"
    0x1131cc4d3 <+49>:  movq   0x4d7aee(%rip), %rbx      ; (void *)0x0000000114598000: objc_msgSend
    0x1131cc4da <+56>:  callq  *%rbx
    0x1131cc4dc <+58>:  movq   0x71e375(%rip), %rsi      ; "_playSystemSound:"
    0x1131cc4e3 <+65>:  movl   $0x3ee, %edx
    0x1131cc4e8 <+70>:  movq   %rax, %rdi
    0x1131cc4eb <+73>:  callq  *%rbx
    0x1131cc4ed <+75>:  cmpq   $-0x1, 0x77877b(%rip)     ; _UIConstraintBasedLayoutLogUnsatisfiable.result + 7
    0x1131cc4f5 <+83>:  jne    0x1131cc541               ; <+159>
    0x1131cc4f7 <+85>:  cmpb   $0x0, 0x77876a(%rip)      ; _UIConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints.__once + 7
    0x1131cc4fe <+92>:  je     0x1131cc51e               ; <+124>
    0x1131cc500 <+94>:  leaq   0x53ba89(%rip), %rdi      ; @"Unable to simultaneously satisfy constraints.ntProbably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) n%@nnWill attempt to recover by breaking constraint n%@nnMake a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.nThe methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful."
    0x1131cc507 <+101>: xorl   %eax, %eax
    0x1131cc509 <+103>: movq   %r14, %rsi
    0x1131cc50c <+106>: movq   %r15, %rdx
    0x1131cc50f <+109>: addq   $0x8, %rsp
    0x1131cc513 <+113>: popq   %rbx
    0x1131cc514 <+114>: popq   %r14
    0x1131cc516 <+116>: popq   %r15
    0x1131cc518 <+118>: popq   %rbp
    0x1131cc519 <+119>: jmp    0x11331930c               ; symbol stub for: NSLog
    0x1131cc51e <+124>: addq   $0x8, %rsp
    0x1131cc522 <+128>: popq   %rbx
    0x1131cc523 <+129>: popq   %r14
    0x1131cc525 <+131>: popq   %r15
    0x1131cc527 <+133>: popq   %rbp
    0x1131cc528 <+134>: retq   
    0x1131cc529 <+135>: leaq   0x778720(%rip), %rdi      ; _UIConstraintBasedLayoutPlaySoundOnUnsatisfiable.__once
    0x1131cc530 <+142>: leaq   0x4fdb59(%rip), %rsi      ; __block_literal_global68
    0x1131cc537 <+149>: callq  0x11331a2a8               ; symbol stub for: dispatch_once
    0x1131cc53c <+154>: jmp    0x1131cc4bc               ; <+26>
    0x1131cc541 <+159>: leaq   0x778728(%rip), %rdi      ; _UIConstraintBasedLayoutLogUnsatisfiable.__once
    0x1131cc548 <+166>: leaq   0x4fdbc1(%rip), %rsi      ; __block_literal_global76
    0x1131cc54f <+173>: callq  0x11331a2a8               ; symbol stub for: dispatch_once
    0x1131cc554 <+178>: jmp    0x1131cc4f7               ; <+85>

What next?

We can use the Xcode debug console output to gather more information than we see it initially provides.

In the above example I'm going to take the following output:

Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7fc82d3e18a0 H:[UIView:0x7fc82aba1210(768)]>

Pull out the UIView's memory address 0x7fd8fe59a440 and use the XCode console to get dig deeper and try to get a better understanding.

Printing views from memory addresses

The memory address 0x7fd8fe59a440 is a pointer to a UIView. Since we know that a UIView has other selectors we can query, we can begin to use these to dig deeper into the object and get a better understanding of which part of our view have auto layout constraints that are not playing nicely.

First we try to look at just the UIView and see if that helps us get a grasp as to which view is causing our troubles.

po 0x7fc82aba1210

If this doesn't provide enough info as the below sample output shows (not very helpful).

(lldb) po 0x7fc82aba1210
<UIView: 0x7fc82aba1210; frame = (0 0; 768 359); autoresize = RM+BM; layer = <CALayer: 0x7fc82d338960>>

Maybe printing it's recursiveDescription will help out and in my case gives me a better idea of which component I'm actually trying to look at.

(lldb) po [0x7fc82aba1210 recursiveDescription] 
<UIView: 0x7fc82aba1210; frame = (0 0; 768 359); autoresize = RM+BM; layer = <CALayer: 0x7fc82d338960>>
   | <MYAPPButton: 0x7fc82d61c800; baseClass = UIButton; frame = (0 0; 768 359); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x7fc82ab96570>>
   |    | <UIImageView: 0x7fc82d3f7b10; frame = (0 0; 0 0); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7fc82d6e7020>>
   | <UIImageView: 0x7fc82d54a1c0; frame = (314 110; 140 140); autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x7fc82d52def0>>

Or if that's not enough context, then we can look at the view's superview and potentially even walk up the view's tree, printing out a different levels trying to understand which component is having trouble with auto layout.

po [[0x7fc82aba1210 superview] recursiveDescription]

Once you've narrowed down which view inside which component is causing you trouble, now it's up to digging and finding the problematic constraint...

Fix it

This part I can't add much color to help you, except to start by looking in your storyboard, xib or code wherever the constraints are being added to the particular view we diagnosed above.

Hopefully this walk-through helps at least a little in diagnosing your auto layout constraint issues.

Happy debugging!

Read More

Running in-app mocha tests within WinJS

I described a while back a scenario about running in-app unit tests. So if you'd like some background on the subject have a look there before reading here.

This post is going to give some specifics about how to run MochaJS tests within a Microsoft Windows JavaScript application (WinJS).

Prerequisites

These steps assume you already have a WinJS application, possibly using the universal template or other. In the end it doesn't matter. As long as you have a project that probably has a default.html file and the ability to add js & css files to.

Get Mocha

You can acquire the mocha library however you want, Bower, Npm, or download it manually from the site (mochajs.org).

Reference Mocha Within Project & App

However you get the mocha source, you need to both add references to the mocha js and css files into your project file either in a *.jsproj file or if using a universal shared app, in the shared project.

Then you need to include a reference to the code in your default.html file.

In my example below you can see I used bower to download the MochaJS library.

The mocha.setup('bdd') tells mocha to use the BDD style of tests which defines the describe(...), it(...), etc functions.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>MyApp.Windows</title>

    <!-- WinJS references -->
    <link href="/js/bower_components/winjs/css/ui-light.css" rel="stylesheet" />
    <script src="/js/bower_components/winjs/js/base.js"></script>
    <script src="/js/bower_components/winjs/js/ui.js"></script>

    <!-- TESTS-->
    <link href="/js/bower_components/mocha/mocha.css" rel="stylesheet" />
    <script src="/js/bower_components/mocha/mocha.js"></script>
    <script>
        mocha.setup('bdd');
    </script>

    <!-- My Project js/css files below... -->

...Rest of default.html file excluded

Create a WinJS Control for hosting Mocha reporting.

Below is a sample WinJS control that can be used to host the mocha html report.

<!DOCTYPE html>
<html>
<head>
    <style>
        #mocha {
            height: 800px;
            width: 600px;
            overflow: scroll;
        }
    </style>
</head>
<body>
    <div class="fragment section1page">
        <section aria-label="Main content" role="main">

            <!-- define a button that we can use to manually run or re-run tests -->
            <button id="mochaTestsRun">Run Tests</button>

            <!-- define a checkbox that allow us to toggle auto-run 
                 of the tests when we start up the app -->
            Auto start <input type="checkbox" id="mochaTestsRunOnStart" />


            <!-- this is a blank div we use to inject U.I. related tests -->
            <div id="testElementContainer"></div>

            <!-- mocha throws the html output in the below div -->
            <div id="mocha"></div>
        </section>
    </div>
</body>
</html>
(function () {
    "use strict";

    var runMochaTests = function() {
        // If you want your tests to verify nothing is leaked globally...
        mocha.checkLeaks();

        // specify any globals that you are OK with your tests leaking
        mocha.globals([
            'someGlobalIAmExpecting'
        ]);

        // start the test run
        mocha.run();
    }

    var ControlConstructor = WinJS.UI.Pages.define("/js/tests/tests.html", {
        // This function is called after the page control contents 
        // have been loaded, controls have been activated, and 
        // the resulting elements have been parented to the DOM. 
        ready: function (element, options) {
            options = options || {};

            // get our possibly already cached value of whether to run the tests on startup.
            var runOnStart = localStorage.getItem("mochaTestsRunOnStart");

            // checkbox to manage auto-run state
            var runOnStartCheckbox = element.querySelector('#mochaTestsRunOnStart');
            runOnStartCheckbox.addEventListener('change', function () {
                localStorage.setItem("mochaTestsRunOnStart", runOnStartCheckbox.checked);
            });

            // button to manually trigger a test run
            var mochaTestsRunButton = element.querySelector('#mochaTestsRun');
            mochaTestsRunButton.addEventListener('click', function(){
                runMochaTests();
            })
            runOnStartCheckbox.checked = runOnStart;

            if (runOnStart && !window.hasRunMochaTestsAtLeastOnce) {
                // this value is used to avoid extra test runs as we navigation around the app.
                // EX: if the test control is on a home pivot - we nav away and come back home
                // we probably don't want to auto-run the tests again. (use the menu button 
                // instead if you want another test run)
                window.hasRunMochaTestsAtLeastOnce = true;
                runMochaTests();
            }

        },
    });

    // The following lines expose this control constructor as a global. 
    // This lets you use the control as a declarative control inside the 
    // data-win-control attribute. 

    WinJS.Namespace.define("Pod.UI.Controls", {
        TestsControl: ControlConstructor
    });
})();

Handle global exceptions

If you write any async code (difficult not to these days) an exception or assertion failure will not be trapped by the internal try/catch mechanism's of Mocha in a Windows WinJS environment.

We have to give Mocha a hint on how to hook into global exceptions.

Mocha tries to attach to the browser's global window.onerror method, and since a WinJS app doesn't use this same handler, we have to forward the exceptions and to mocha's attached window.onerror handler.

In you're default.js or wherever you configure the app you can attach to the WinJS.Application.onerror and after some exception massaging we can hand the exceptions to mocha so when a test fails it can be reported correctly.

    WinJS.Application.onerror = function (ex) {

        var errorMessage, errorLine, errorUrl;
        if (ex.detail.errorMessage) {
            errorMessage = ex.detail.errorMessage;
            errorLine = ex.detail.errorLine;
            errorUrl = ex.detail.errorUrl;
        } else if (ex &&
            ex.detail &&
            ex.detail.exception &&
            ex.detail.exception.stack) {
            errorMessage = ex.detail.exception.stack;
            errorLine = null;
            errorUrl = null;
        }

        // if window.onerror exists, assume mochajs is here and call it's error handler
        // This may be a poor assumption because 3rd party libraries could also attach
        // their handlers, but it's working for me so far...
        if (window.onerror && errorMessage) {
            window.onerror(errorMessage, errorLine, errorUrl);
            
            // return true signalling that the error's been 
            // handled (keeping the whole app from crashing)
            return true;
        }

        // if we get here, assuming mochajs isn't running
        // let's log out the errors...
        try {
            var exMessage = JSON.stringify(ex, null, '  ');
            console.error(exMessage);
        } catch (e) {
            // can't JSON serialize exception object here (probably circular reference)
            // log what we can...
            console.error(ex);
            console.error(e);
        }

        // I like to be stopped while debugging to possibly
        // poke around and do further inspection
        debugger;
    }

Reference the test control.

While developing out the application, I like to throw it front and center in the first hub of my apps home page hub control.

Here's an example of how to reference the above control:

<head>
    <meta charset="utf-8" />
    <title>hubPage</title>

    <link href="/pages/hub/hub.css" rel="stylesheet" />
    <script src="/js/tests/tests.js"></script>
</head>

...page details trimmed for brevity...

            <div class="hub" data-win-control="WinJS.UI.Hub">

                <div class="sectionTests"
                     data-win-control="WinJS.UI.HubSection"
                     data-win-options="{ isHeaderStatic: true }"
                     data-win-res="{ winControl: {'header': 'TestSection'} }">
                    <div id="sectionTestscontenthost" data-win-control="MyApp.Testing.TestsControl"></div>
                </div>
            </div>

...rest of page details trimmed for brevity...

If you manage to get everything wired up correctly above, when you run the app (F5) your mocha tests should be all set and run automatically. Oh wait, let's not forget to add a mocha test :)...

describe('Mocha test spike', function(){

    it("should report a passing test", function(){
      // doing nothing should be a passing test
    });

    it("should fail on a synchronous exception", function(){
        throw new Error("Some test error to make sure mocha reports a test failure")
    });

    it("should fail on an asynchronous exception", function(done){
        setTimeout(function(){
            throw new Error("Some test error to make sure mocha reports an async test failure")
            done();
        }, 100);
        throw new Error("Some test error to make sure mocha reports a test failure")
    });

});

Save the above as your first test file, include it so it runs on startup and verify your tests run and report correctly within the test control.

Happy testing!

Read More