笑话 TypeScript 类“没有重载需要 1 个类型参数"; [英] Jest mocking TypeScript class "No overload expects 1 type arguments"

查看:22
本文介绍了笑话 TypeScript 类“没有重载需要 1 个类型参数";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Jest 模拟 TypeScript 类,我显然正在做某事,因为收到以下错误:

I'm trying to mock a TypeScript class with Jest and I'm obviously doing something because receive the following error:

error TS2743: No overload expects 1 type arguments, but overloads do exist that expect either 0 or 2 type arguments.

这是我的代码:

Foo.ts

export default class Foo {
  bar(): number {
    return Math.random()
  }
}

Foo.test.ts

Foo.test.ts

import Foo from './Foo'

describe('Foo', () => {
  it("should pass", () => {
    const MockFoo = jest.fn<Foo>(() => ({
      bar: jest.fn(() => {
        return 123
      }),
    }))
  })
})

完整的错误:

TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
src/Foo.test.ts:6:29 - error TS2743: No overload expects 1 type arguments, but overloads do exist that expect either 0 or 2 type arguments.

6     const MockFoo = jest.fn<Foo>(() => ({
                              ~~~

更新

如果有任何相关性,这是我的 Jest 配置:

If it is of any relevance, this is my Jest config:

module.exports = {
  moduleFileExtensions: ['ts', 'js'],
  transform: {
    '^.+\.ts$': 'ts-jest',
  },
  testMatch: ['**/src/**/*.test.(ts)'],
  testEnvironment: 'node',
};

推荐答案

Jest 具有以下 jest.fn 的签名:

Jest has the following signature for jest.fn:

/**
 * Creates a mock function. Optionally takes a mock implementation.
 */
function fn<T, Y extends any[]>(implementation?: (...args: Y) => T): Mock<T, Y>;

因此,您需要为 args 指定类型数组,在您的特定情况下,您可以只传递一个空数组,因为您的实现函数中没有 args.

So you need to specify the array of types for the args, in your particular case you could just pass an empty array as there are no args in your implementation function.

const MockFoo = jest.fn<Foo, []>(() => ({

这篇关于笑话 TypeScript 类“没有重载需要 1 个类型参数";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆