typescript 和 Jest : mocking throws typerror because its using the wrong overload

标签 typescript unit-testing jestjs

在 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/

相关文章:

javascript - 当我们不知道 Typescript 中的属性名称时,以编程方式推送到 Any 类型的数组

javascript - 当 observable 为空时,骨架文本不显示

javascript - 使用 Jasmine 进行 http post 方法的单元测试用例

node.js - 如何在Service构造函数中对Controller和模拟@InjectModel进行单元测试

react-native - 使用react-native-paper 在 Expo 应用程序中进行 Jest 测试

angular - 如何在 Angular 应用程序中使用 powerbi-client 依赖项,而不破坏 Jest 测试?

arrays - 带有多个属性上的对象的 typescript 排序数组

node.js - 如何修复 : "TypeError: Cannot read property ' Id' of undefined"in NodeJS (TypeScript)

python - 使用 dict 进行单元测试 __repr__ 的正确方法

c# - async/await 在单元测试中优于阻塞的优势