Typescript原型补丁和jest

问题描述 投票:0回答:1

我有一个问题,就是jest不能正确识别合并的接口。

我有一个来自@types库的decleration文件,安装在npm.The实现是由环境实现的,在生产系统中作为一个全局,我无法访问它(想想看 window 作为浏览器的等价物,虽然在你的代码中没有定义,但当js在浏览器中运行时还是存在的)。)

// @types/Foo/index.d.ts

interface Foo {
  A();
}

然后,我使用prototype向该接口添加更多的功能。

// src/monkeypatch.ts

declare global {
  interface Foo {
    B();
  }
}
Foo.prototype.B = function() {};

并在我的代码中使用它

// main.ts
import 'src/monkeypatch.ts'; // side effects import
// src/Bar.ts

class Bar {
  bar(foo: Foo) {
    foo.B();
  }
}

到目前为止,一切都能按照预期工作,我的编辑器很高兴,tsc也很高兴,一切都在生产中运行得很好。

现在我想设置单元测试并模拟单元测试的实现,我创建了一个实现。

// mocks/Foo.ts

class FooImpl implements Partial<Foo> {
  A() {};
}

export { FooIMpl as Foo };

而测试文件

// src/Bar.spec.ts

import { Foo } from '../mocks/Foo';
(global as any).Foo = Foo;
import 'monkeypatch';  // patches A with additional methods

import { Bar } from 'Bar';

new Bar().bar(new Foo());

但是我得到了下面的错误,好像它不知道接口合并的事实,也不知道它被打了补丁。

类型'FooImpl'的参数不可分配给类型'Foo'的参数.类型'FooImpl'缺少了类型'Foo'的以下属性: B.ts(2345)

将通话地点改为 bar(new Foo() as any); 是一个变通方法,并导致测试通过,但它闻起来很可怕,我希望这能正确工作,我错过了什么?

另一个问题是,我似乎必须使用Partial才能让编译器满意,否则我得到以下错误:Class 'FooImpl' incorrectly implements interface 'Foo'.Type 'FooImpl' is missing the following properties from type 'Foo': B。

typescript unit-testing prototype jest ts-jest
1个回答
0
投票

看来要打补丁了 是公认的但你的 FooImpl 只是定义 A(){} 而不是 B(){} 如你所言 src/monkeypatch.ts.

扩容后的阿福变成了

class Foo {
  A() {}
  B() {}
}

所以要分配 FooImplFoo 你应该同时实施。

© www.soinside.com 2019 - 2024. All rights reserved.