Given the following in a Jest test.
const mockDirListing: string[] = ['sdafd', 'sfdf'];
const mockReaddirSync = jest.spyOn(fs, 'readdirSync');
mockReaddirSync.mockReturnValue(mockDirListing);
TypeScript will present the following error:
Argument of type 'string[]' is not assignable to parameter of type 'Dirent[]'.
Type 'string' is not assignable to type 'Dirent'.ts(2345)
The mocked instance has the type
jest.SpyInstance<fs.Dirent[], [fs.PathLike, {
encoding?: string;
withFileTypes: true;
}]>
But the overload I would like to use in the SpyInstance is
jest.SpyInstance<string[], [fs.PathLike, {
encoding?: string;
withFileTypes: true;
}]>
Anyone come across this before?
The same can be said about any classes with overloads
class Testing {
foo(a: string): string;
foo(a: number): string;
foo(a: number | string): string {
if (typeof a === 'string') return a;
else if (a) return arguments.toString();
}
}
test('testing', () => {
const testing = new Testing();
const mocked = jest.spyOn(testing, 'foo');
mocked.mockImplementation((a: string) => a.toString());
});
throws
Argument of type '(a: string) => string' is not assignable to parameter of type '(a: number) => string'.
Types of parameters 'a' and 'a' are incompatible.
Type 'number' is not assignable to type 'string'.ts(2345)
How can I use the type signature of the first overload?
We'll after looking into it, seems like the best you can really do is something like
const stub = (sinon.stub(fs, 'readdir') as unknown) as sinon.SinonStub<any[], Promise<Dirent[]>>;
Coercing the type to the once you specify.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.