testing-library / preact-hooks-testing-library

Simple and complete Preact hooks testing utilities that encourage good testing practices.
MIT License
56 stars 10 forks source link

Fix typing for parity with React #16

Open kevinweber opened 2 years ago

kevinweber commented 2 years ago

Fixes in this PR get the typing closer to what React's testing library does and thereby makes migrations from React to Preact easier. When I migrated from React to Preact, a TS error appeared as soon as I imported renderHook from the Preact testing library:

Screen Shot 2022-02-02 at 3 53 47 PM

The error says that result.current could possibly be undefined, meaning I need to unfortunately refactor result.current(yo) to result.current?.(yo).

At first this issue makes sense because the resultContainer function has an initialValue argument that might be undefined and also the value of let value might be undefined. However, the library actually never calls resultContainer with an argument, justifying the removal of initialValue as a potential argument.

That doesn't solve the potential undefined value though. For this, I'm following the pattern in React's resultContainer by assigning value as R. This way types are safe.

I verified type-safety locally in one of the tests. When I change…

const { result } = renderHook(() => useCounter());
...
expect(result.current.count).toBe(1);

…to…

const { result } = renderHook(() => 'different');
...
expect(result.current.count).toBe(1);

…TS throws an error for result.current.count, saying that result.current can't have a property count – which is correct because result.current is now of type string.