Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Using Jest without a package.json#
I wanted to try out Jest for writing JavaScript unit tests, in a project that wasn’t set up with package.json and other NPM related things.
Jest looks for *.spec.js tests in a __tests__ directory. It expects to find configuration in a package.json file but it can be passed configuration using the -c option - which can be a path to a JSON configuration file or can be a JSON literal.
I created a file I wanted to test in plugins.js which looked like this. The module.exports at the bottom was required so Jest could later import the code:
1var datasette = datasette || {};2datasette.plugins = (() => {3 var registry = {};4 return {5 register: (hook, fn, parameters) => {6 if (!registry[hook]) {7 registry[hook] = [];8 }9 registry[hook].push([fn, parameters]);10 },11 call: (hook, args) => {12 args = args || {};13 var results = [];14 (registry[hook] || []).forEach(([fn, parameters]) => {15 /* Call with the correct arguments */16 var result = fn.apply(fn, parameters.map(parameter => args[parameter]));17 if (result !== undefined) {18 results.push(result);19 }20 });21 return results;22 }23 };24})();25
26module.exports = datasette;Then I created __tests__/plugins.spec.js with this:
1const datasette = require("../plugins.js");2
3describe("Datasette Plugins", () => {4 test("it should have datasette.plugins", () => {5 expect(!!datasette.plugins).toEqual(true);6 });7 test("registering a plugin should work", () => {8 datasette.plugins.register("numbers", (a, b) => a + b, ["a", "b"]);9 var result = datasette.plugins.call("numbers", { a: 1, b: 2 });10 expect(result).toEqual([3]);11 datasette.plugins.register("numbers", (a, b) => a * b, ["a", "b"]);12 var result2 = datasette.plugins.call("numbers", { a: 1, b: 2 });13 expect(result2).toEqual([3, 2]);14 });15});Now I can run Jest in the same directory as plugins.js like this:
1% npx jest -c '{}'2 PASS __tests__/plugins.spec.js3 Datasette Plugins4 ✓ it should have datasette.plugins (3 ms)5 ✓ registering a plugin should work (1 ms)6
7Test Suites: 1 passed, 1 total8Tests: 2 passed, 2 total9Snapshots: 0 total10Time: 1.163 s11Ran all test suites.