gpt4 book ai didi

typescript - Jest spyOn 不适用于 typescript : "Property ' mockRestore' is missing in type 'Spy' "

转载 作者:行者123 更新时间:2023-12-04 01:16:39 25 4
gpt4 key购买 nike

使用时 spyOn使用 Jest 和 typescript ,我收到此类型错误:

Type 'Spy' is not assignable to type 'SpyInstance<{}>'. Property 'mockRestore' is missing in type 'Spy'.



这是导致它的代码示例:
class A {
foo = () => this.bar() + 1;
bar = () => 1;
}

test('should pass', () => {
const a = new A();
let barSpy: jest.SpyInstance;
barSpy = spyOn(a, 'bar');
a.foo();
expect(barSpy).toHaveBeenCalled();
});

当我运行此示例时,测试通过,但 typescript 编译器失败。

最佳答案

简答

全局spyOn(...)函数返回 jasmine.Spy不是 jest.SpyInstance .据我所知,这样做的原因是 ease migration from Jasmine to Jest.

这里有两个选项:

let barSpy: jest.SpyInstance;
barSpy = jest.spyOn(a, 'bar'); // <--- explicitly use jest.spyOn

// or

let barSpy: jasmine.Spy; // <--- use jasmine.Spy as your type
barSpy = spyOn(a, 'bar');

进一步说明

node_modules\@types\jest\index.d.ts 文件具有 Jest 类型定义。通过查看它们,我们可以看到 spyOn 的两个实现.
  • spyOn返回 jest.SpyInstancejest 里面命名空间。
  • spyOn返回 jasmine.Spy位于全局命名空间中。

  • 除非您正在从 Jasmine 迁移到 Jest,否则我会使用 jest.spyOn函数而不是全局函数。

    关于typescript - Jest spyOn 不适用于 typescript : "Property ' mockRestore' is missing in type 'Spy' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53989032/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com