在 Jest 测试中给出以下内容。
const mockDirListing: string[] = ['sdafd', 'sfdf'];
const mockReaddirSync = jest.spyOn(fs, 'readdirSync');
mockReaddirSync.mockReturnValue(mockDirListing);
TypeScript 将出现以下错误:
Argument of type 'string[]' is not assignable to parameter of type 'Dirent[]'.
Type 'string' is not assignable to type 'Dirent'.ts(2345)
模拟实例具有类型
jest.SpyInstance<fs.Dirent[], [fs.PathLike, {
encoding?: string;
withFileTypes: true;
}]>
但是我想在 SpyInstance 中使用的重载是
jest.SpyInstance<string[], [fs.PathLike, {
encoding?: string;
withFileTypes: true;
}]>
有人遇到过这个吗?
对于任何具有重载的类也可以这样说
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());
});
抛出
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)
如何使用第一个重载的类型签名?
最佳答案
我们调查之后,似乎你真正能做的最好的事情就是这样
const stub = (sinon.stub(fs, 'readdir') as unknown) as sinon.SinonStub<any[], Promise<Dirent[]>>;
将类型强制为您指定的类型。
关于 typescript 和 Jest : mocking throws typerror because its using the wrong overload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59794892/