简体   繁体   English

测试无法运行,因为在尝试测试类型检查时,打字稿会引发错误

[英]Tests don't run because typescript throws error when trying to test type checking

Trying to test to make sure that a typed variable can only be assigned certain values. 尝试进行测试以确保只能为类型化变量分配某些值。 Is there a way to use jest to throw an error if an invalid value is assigned, without typescript preventing the tests from running and throwing an error before tests run? 如果分配了无效的值,是否有一种方法可以通过玩笑来引发错误,而不会导致打字稿阻止测试运行并在测试运行之前引发错误?

In class constructor:
defaultValue: string | null

In test:
expect(() => instance.defaultValue = 100).toThrow()

I expect that the test should run and acknowledge that this does throw an error, but the error is thrown before the test runs, preventing all tests from running. 我希望测试能够运行并确认确实会引发错误,但是该错误会在测试运行之前抛出,从而阻止所有测试运行。

Typescript is not a runtime type checker, it is a compile time type checker. Typescript不是运行时类型检查器,它是编译时类型检查器。 This means that all types are checked before the code is converted to javascript and if there is a type error the compile fails. 这意味着在将代码转换为javascript之前,将检查所有类型,并且如果存在类型错误,则编译将失败。 If your class takes data from an unverified source, IE an API you cannot check that with typescript. 如果您的班级从未经验证的来源(即IE API)获取数据,则无法使用打字稿进行检查。

Your test implies 1 of 2 things: 您的测试意味着2件事之一:

Either Your constructor is meant to consume data that is only known at runtime, but should always be a string and must throw an error if it is not. 要么您的构造函数打算使用仅在运行时才知道的数据,但应始终为字符串,如果不是,则必须引发错误。 In that case you may cast your class to any this removes type checking completely for this object, but it will allow you test that your class throws an error. 在这种情况下,您可以将您的类强制转换为any对象,这将完全删除此对象的类型检查,但是它将允许您测试类是否抛出错误。

const instance = new (MyClass as any)(42) // throws an error

Or your class is only used by data the developer explicitly provides to it and your test only verifies that typescript will not allow a developer to make a mistake. 或者您的类仅由开发人员显式提供给它的数据使用,而您的测试仅验证打字稿不会允许开发人员犯错误。 In that case, this is not a useful test and you should probably remove it. 在这种情况下,这不是有用的测试,您应该删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM