Use TypeScript to Reduce Your Unit Tests | by Voon Ming Hann | Apr, 2022

Pace up your growth time by lowering testing time

Photograph by Lucian Alexe on Unsplash

Some of the frequent arguments I’ve heard from those that haven’t adopted TypeScript is “If issues work in JavaScript why would I write it in TypeScript?”. Their curiosity stage drops even additional once they noticed the additional codes that they’ll have to jot down.

However I’ll present you a small instance of how TypeScript helps to scale back the variety of check circumstances whereas protecting the standard of your undertaking.

Now we have a util operate that accepts a string or quantity however doesn’t settle for an array:

const util = (val) => 
if (Array.isArray(val))
throw new Error("Array just isn't settle for.");

return val

The minimal check we’ll write is:

describe("util", () => 
it("Ought to return a string", () =>
count on(util("abc")).toBeTypeof("string");
it("Ought to return a quantity", () =>
count on(util(123)).toBeTypeof("quantity");
it("Ought to error", () =>
count on(() => util([])).toThrow();

if we do that in TypeScript:

const util = <T>(val: T extends any[] ? "array just isn't accepted" : T) => 
return val;
util('hi there');
util([1,2,3]) //error
util([]) //error

Right here’s a sneak peek on the Demo. It can throw errors in the course of the runtime verify and you may safely take away your exams!

Think about the compound advantages:

  1. You’ll get immediate suggestions for errors.
  2. You’ll write fewer check circumstances thus it takes lesser time to keep up these exams.
  3. You saved time operating fewer exams regionally earlier than pushing the code.
  4. You’ve fewer exams within the ci pipeline, which implies sooner construct time.

Now, occasions that with x variety of devs in your group.

TypeScript is sweet!

More Posts