2016-12-11

TypeScript Testing of jQuery Ajax from Node.js

After a decent hiatus from web dev, I'm back at it. With last week's release of TypeScript 2.1 which has downlevel support for async and the advancement of the fetch api standard, it feels like a fun time to get reacquainted. The single-page app I'm going to be working on is still using jQuery ajax for communication. I was curious if I could write some tests for our web api that executed on Node.js. The testing frameworks being used support both browser and Node.js execution, but challenge accepted.

It turns out that jQuery is really meant for the browser and not Node.js. The fetch api works equally well on both, but I'll give details in my next blog post. After some searches, it turns that you need to initialize jQuery with a window object. You can create a fake window object with jsdom. Here is the solution I used:

jquery-tests.ts

I'm enjoying some snow in beautiful Canada right now while working remotely, so here is the output:

output.txt

This is the tsconfig.js for the project:

tsconfig.js

and the FreeGeoIP.d.ts generated from the sample json:

FreeGeoIP.d.ts

These are the npm packages I installed:

install.sh