nodejs / node-core-test

Node 18's node:test, as an npm package
Other
95 stars 10 forks source link

fix: improve types #42

Open hongaar opened 1 year ago

hongaar commented 1 year ago

Various improvements to the TypeScript types:

I tried re-using the types from @types/node but these also seem incomplete/incorrect at places (e.g. SuiteFn) so instead based these changes on the README of this package.

Suggestions for further improvements:

If these are welcome, happy to contribute another PR addressing those.

hongaar commented 1 year ago

@MoLow thanks for the review ~I can't find any reference for the fn return type signature of TestFn though?~

Edit: misinterpreted your suggestion 🤦 will apply your changes!

Edit2: couldn't get this to work, tried:

type TestFn =
  | ((t: TestContext, done: (result?: any) => void) => any)
  | ((t: TestContext) => Promise<any>)

test(async (t) => {})

Which yields:

't' is declared but its value is never read. ts(6133)
Parameter 't' implicitly has an 'any' type, but a better type may be inferred from usage. ts(7044)

Making TestFn generic doesn't change much.

hongaar commented 1 year ago

In order to test these changes, I wrote a quick tsd test in test/test.test-d.ts:

import { expectType } from "tsd";
import test, { describe, it } from "../lib/test.js";

// # test()

// Parameters
expectType<void>(await test());
expectType<void>(await test("name", { only: true }));
expectType<void>(await test("name", { only: true }, () => {}));
expectType<void>(await test({ only: true }));
expectType<void>(await test({ only: true }, () => {}));
expectType<void>(await test("name", () => {}));
expectType<void>(await test(() => {}));

// TestFn
expectType<Promise<void>>(test(() => {}));
expectType<void>(await test((t) => {}));
expectType<void>(await test(async (t) => {}));
expectType<void>(await test((t, done) => done()));
expectType<void>(await test(async (t, done) => done())); // Test will fail

// # describe()

// Parameters
expectType<void>(describe());
expectType<void>(describe("name", { only: true }));
expectType<void>(describe("name", { only: true }, () => {}));
expectType<void>(describe({ only: true }));
expectType<void>(describe({ only: true }, () => {}));
expectType<void>(describe("name", () => {}));
expectType<void>(describe(() => {}));

// # it()

// Parameters
expectType<void>(it());
expectType<void>(it("name", { only: true }));
expectType<void>(it("name", { only: true }, () => {}));
expectType<void>(it({ only: true }));
expectType<void>(it({ only: true }, () => {}));
expectType<void>(it("name", () => {}));
expectType<void>(it(() => {}));

In package.json:

{
  "scripts": {
    "test:types": "tsd --files test/test.test-d.ts"
  }
}

And run with:

npm i -D tsd
npm run test:types

If wanted, I will commit these changes (and add test:types to the test script) in a separate PR.