404usernamenotfound
404usernamenotfound

Reputation: 190

Vitest importActual: Jest gets types, but Vitest gives "... is of type unknown"

I'm migrating from jest to vitest. In the process, I am converting these:

// Jest
const myLib = jest.requireActual("mylib.js")

to these:

// Vitest
const myLib = await vi.importActual("myLib.js")

Great, except with Jest, I get no type errors, but with Vitest, I get:

TS18046: myLib is of type unknown

I can access members of myLib, and I can see that they are typed correctly, but any access on myLib causes the error:

// Thing[] is inferred. Error is on **myLib**.things
const things: Thing[] = myLib.things

When investigating (by simply hovering over myLib in WebStorm) the type in each scenario, I see that Jest gives any for myLib's type, while Vitest gives unknown.

I have noImplicitAny: true in my tsconfig.json, so I would think I should get an error on any as well.

But anyway, why is there a difference, how can TypeScript figure out that myLib.things is of type Thing[] if myLib itself is unknown, and how am I supposed to do it?

Upvotes: 3

Views: 693

Answers (2)

Bastiat
Bastiat

Reputation: 797

I just ran into this myself and code quality checks were yelling at me. I needed forwardRef in a mock but, as you ran into, await vi.importActual('react') was unknown;

solution

import React from 'react';
vi.mock('my-module', async () => {
    const { forwardRef } = await vi.importActual<typeof React>('react');
    ...
});

So, if you have a type definition for that module, you can just use that, but it wont infer.

Upvotes: 1

404usernamenotfound
404usernamenotfound

Reputation: 190

I guess a simple way to deal with this is to simply do await vi.importActual("myLib.js") as Record<{a: b}>, where a is some member you're accessing within the test and b is the type of that member. unknown may be better than any here since it forces you to be aware of this.

However, I still don't understand how Thing[] could possibly be inferred from unknown.

Upvotes: 0

Related Questions