Skip to content

Instantly share code, notes, and snippets.

@ctaggart
Last active December 2, 2019 15:05
Show Gist options
  • Save ctaggart/87fea160bea50c11a36954bd4dc865c5 to your computer and use it in GitHub Desktop.
Save ctaggart/87fea160bea50c11a36954bd4dc865c5 to your computer and use it in GitHub Desktop.
jQuery Tests in TypeScript on Node.js

It turns out that jQuery isn't very easy to use on Node.js. I simply wanted to run some tests there. Here is how I got it working. Create a test folder. Save the tsconfig.json & jquery-tests.ts to it. Install the dependencies.

tsc -p test
mocha .\test\jquery-tests.js
#!/bin/sh -e
npm install --save jquery
npm install --save-dev jsdom
npm install --save-dev chai
npm install --save-dev mocha
npm install --save-dev @types/node
npm install --save-dev @types/jsdom
npm install --save-dev @types/chai
npm install --save-dev @types/mocha
import * as mocha from "mocha";
import {assert} from "chai";
import * as jsdom from "jsdom";
import * as jquery from "jquery";
interface FreeGeoIP {
ip: string;
country_code: string;
country_name: string;
region_code: string;
region_name: string;
city: string;
zip_code: string;
time_zone: string;
latitude: number;
longitude: number;
metro_code: number;
}
describe("jquery tests", () => {
it("get ip", done => {
// window is required for jQuery to work in Node.js
// http://stackoverflow.com/a/36238302/23059
jsdom.env("", (err, window) => {
const $ = require("jquery")(window) as JQueryStatic;
$.ajax({type: "GET", url: "http://freegeoip.net/json/"}).done(data => {
const geoip = data as FreeGeoIP;
console.log(data);
console.log("ip is " + geoip.ip);
assert.isString(geoip.ip);
assert.isString(geoip.country_code);
done();
});
});
});
});
{
"compilerOptions": {
"module": "commonjs",
"sourceMap": true
},
"files": [
"jquery-tests.ts"
],
"typeRoots": [
"../node_modules/@types"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment