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?

myol
  • 8,857
  • 19
  • 82
  • 143
  • 1
    You can check my answer [here](https://stackoverflow.com/questions/68887818/using-sinon-spy-when-two-methods-have-the-same-name-but-different-arguments/69130575#69130575) – andreyunugro Nov 02 '21 at 09:44

1 Answers1

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']);
myol
  • 8,857
  • 19
  • 82
  • 143