Hacker News new | ask | show | jobs
by vnglst 3439 days ago
"Unit tests in JavaScript

Writing unit tests in TypeScript can sometimes be troublesome and confusing. Especially when mocking dependencies and using spies."

Anybody know why unit tests are difficult in TypeScript?

1 comments

Typescript is strictly typed, so things that need to look like a type but aren't actually that type, like mocks and spies, can be troublesome.
Exactly. TSC usually complains on all stubs, mocks and spies or it takes massive amounts of time to properly annotate the types. Unit tests quickly don't follow AAA rule, are hard to read (and understand) and the required time investment is not worth it. I find using TypeScript for source code and JavaScript for unit tests much more convenient.
I had the same problem until a recent TS release introducing the keyof feature. You can create a TypeScript type that automatically convert a class definition to stubs.

  type StubInstance<T> = {
      [P in keyof T]: sinon.SinonStub;
  };
I've gone both ways. Writing the tests in typescript is doable, but making sure you have good ts declarations for all the unit test libraries is key. I've had good luck with mocha, chai, sinon and their respective @types.