gpt4 book ai didi

javascript - 如何使用 Flow 类型提示和 Jest 处理错误

转载 作者:行者123 更新时间:2023-11-29 15:12:23 25 4
gpt4 key购买 nike

我有一个这样定义的类:

class MyClass{
constructor(data:Array<any>){
...
}
}

Jest 中的基本测试设置如下:

test('bad args', () => {
expect(new MyClass()).toThrow();
expect(new MyClass({})).toThrow();
expect(new MyClass('string')).toThrow();
});

我希望这些会出错,因为类型提示不允许空的构造函数参数,并且期望第一个参数是数组而不是对象或字符串。

任何人都可以帮助解释我如何说服 Jest 通过 Flow 和类型不正确的错误来运行代码吗?

编辑:我还运行了 flow-typed install jest@23.6.0//correct jest version

最佳答案

doc states that :

Babel will take your Flow code and strip out any type annotations.

因此,Flow 可以帮助您在构建之前 发现错误的调用(通常在开发时,在 ide 中)。一旦你运行 flow在您的项目中 - 您可以发现签名不匹配的地方。

编译流程注解被删除后,您拥有了纯 javascript。

因此,如果您的构造函数接受 any arg,但只有数组是有效的,您可以明确声明:

class MyClass {
constructor(data:*) {
if (!Array.isArray(data)) {
throw new Exception('Bad argument');
}
}
}

如果您指定 data:Array<any>,上述代码库将起作用同样,但是您会在编译时看到错误(因此您可以找出应该责备的人 :))。

关于javascript - 如何使用 Flow 类型提示和 Jest 处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53206034/

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