0

I have the following code

import { readdir } from 'fs/promises';

const files: string[] = await readdir('/original/file/path');

Which I am trying to test

import * as fsPromisesModule from "fs/promises";

stub(fsPromisesModule, "readdir").callsFake(async (): Promise<string[]> => ['/test/file/path']);

but I get the following error

Type 'Promise<string[]>' is not assignable to type 'Promise<Dirent[]>'.
  Type 'string[]' is not assignable to type 'Dirent[]'.
    Type 'string' is not assignable to type 'Dirent'.ts(2322)

The promises.d.ts file contains the following signatures

    function readdir(
        path: PathLike,
        options?:
            | (ObjectEncodingOptions & {
                  withFileTypes?: false | undefined;
              })
            | BufferEncoding
            | null
    ): Promise<string[]>;

    function readdir(
        path: PathLike,
        options:
            | {
                  encoding: 'buffer';
                  withFileTypes?: false | undefined;
              }
            | 'buffer'
    ): Promise<Buffer[]>;

    function readdir(
        path: PathLike,
        options?:
            | (ObjectEncodingOptions & {
                  withFileTypes?: false | undefined;
              })
            | BufferEncoding
            | null
    ): Promise<string[] | Buffer[]>;

    function readdir(
        path: PathLike,
        options: ObjectEncodingOptions & {
            withFileTypes: true;
        }
    ): Promise<Dirent[]>;

The last signature is being used in the stub but I want to use the first signature. How can I tell TypeScript that is the signature I want to use in my tests?

1

1 Answer 1

0

As per @andreyunugros linked answer, the following worked;

(stub(fsPromisesModule, "readdir") as unknown as SinonStub<[p: PathLike], Promise<string[]>>).callsFake(async (): Promise<string[]> => (['/file/path/name']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.