开玩笑地嘲笑TypeScript类“没有重载需要1个类型参数". [英] Jest mocking TypeScript class "No overload expects 1 type arguments"

查看:106
本文介绍了开玩笑地嘲笑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天全站免登陆